package handlers

import (
	"net/http"
	"strings"

	"gauth-central/internal/services"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type EducationHandler struct {
	educationService *services.EducationService
}

func NewEducationHandler(educationService *services.EducationService) *EducationHandler {
	return &EducationHandler{educationService: educationService}
}

type CreateEducationRequest struct {
	BetweenYears string `json:"between_years"`
	Title        string `json:"title"`
	Content      string `json:"content"`
	ResumeID     string `json:"resume_id"`
	IsActive     *bool  `json:"is_active"`
}

type UpdateEducationRequest struct {
	BetweenYears *string `json:"between_years"`
	Title        *string `json:"title"`
	Content      *string `json:"content"`
	ResumeID     *string `json:"resume_id"`
	IsActive     *bool   `json:"is_active"`
}

// GetAllEducations godoc
// @Summary Get all active educations
// @Description Retrieve a list of active education entries
// @Tags resume
// @Produce json
// @Param resume_id query string false "Resume ID"
// @Success 200 {array} models.Education
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /educations [get]
func (h *EducationHandler) GetAllEducations(c *gin.Context) {
	resumeID := strings.TrimSpace(c.Query("resume_id"))
	var resumeIDPtr *string
	if resumeID != "" {
		resumeIDPtr = &resumeID
	}
	items, err := h.educationService.GetAllEducations(resumeIDPtr, true)
	if err != nil {
		status := http.StatusInternalServerError
		c.JSON(status, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, items)
}

// AdminGetAllEducations godoc
// @Summary Get all educations (Admin)
// @Description Retrieve a list of all education entries including inactive ones
// @Tags admin
// @Security ApiKeyAuth
// @Produce json
// @Param resume_id query string false "Resume ID"
// @Success 200 {array} models.Education
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /admin/educations [get]
func (h *EducationHandler) AdminGetAllEducations(c *gin.Context) {
	resumeID := strings.TrimSpace(c.Query("resume_id"))
	var resumeIDPtr *string
	if resumeID != "" {
		resumeIDPtr = &resumeID
	}
	items, err := h.educationService.GetAllEducations(resumeIDPtr, false)
	if err != nil {
		status := http.StatusInternalServerError
		c.JSON(status, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, items)
}

// AdminGetEducationByID godoc
// @Summary Get an education by ID (Admin)
// @Description Retrieve details of a specific education entry
// @Tags admin
// @Security ApiKeyAuth
// @Produce json
// @Param id path string true "Education ID"
// @Success 200 {object} models.Education
// @Failure 404 {object} map[string]string
// @Router /admin/educations/{id} [get]
func (h *EducationHandler) AdminGetEducationByID(c *gin.Context) {
	id := c.Param("id")
	item, err := h.educationService.GetEducationByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, item)
}

// CreateEducation godoc
// @Summary Create a new education (Admin)
// @Description Create a new education entry
// @Tags admin
// @Security ApiKeyAuth
// @Accept json
// @Produce json
// @Param request body CreateEducationRequest true "Education Request"
// @Success 201 {object} models.Education
// @Failure 400 {object} map[string]string
// @Router /admin/educations [post]
func (h *EducationHandler) CreateEducation(c *gin.Context) {
	var req CreateEducationRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	req.BetweenYears = strings.TrimSpace(req.BetweenYears)
	req.Title = strings.TrimSpace(req.Title)
	req.Content = strings.TrimSpace(req.Content)
	if req.BetweenYears == "" || req.Title == "" || req.Content == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "between_years, title, and content are required"})
		return
	}

	isActive := false
	if req.IsActive != nil {
		isActive = *req.IsActive
	}

	resumeUUID, parseErr := parseUUIDPtr(req.ResumeID)
	if parseErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid resume id"})
		return
	}
	item, err := h.educationService.CreateEducation(req.BetweenYears, req.Title, req.Content, resumeUUID, isActive)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, item)
}

// UpdateEducation godoc
// @Summary Update an education (Admin)
// @Description Update an existing education entry
// @Tags admin
// @Security ApiKeyAuth
// @Accept json
// @Produce json
// @Param id path string true "Education ID"
// @Param request body UpdateEducationRequest true "Education Request"
// @Success 200 {object} models.Education
// @Failure 400 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /admin/educations/{id} [put]
func (h *EducationHandler) UpdateEducation(c *gin.Context) {
	id := c.Param("id")
	var req UpdateEducationRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if req.BetweenYears != nil {
		trimmed := strings.TrimSpace(*req.BetweenYears)
		req.BetweenYears = &trimmed
	}
	if req.Title != nil {
		trimmed := strings.TrimSpace(*req.Title)
		req.Title = &trimmed
	}
	if req.Content != nil {
		trimmed := strings.TrimSpace(*req.Content)
		req.Content = &trimmed
	}
	if req.ResumeID != nil {
		trimmed := strings.TrimSpace(*req.ResumeID)
		req.ResumeID = &trimmed
	}

	var resumeUUIDPtr *uuid.UUID
	if req.ResumeID != nil {
		parsed, parseErr := parseUUIDPtr(*req.ResumeID)
		if parseErr != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "invalid resume id"})
			return
		}
		resumeUUIDPtr = parsed
	}
	item, err := h.educationService.UpdateEducation(id, req.BetweenYears, req.Title, req.Content, resumeUUIDPtr, req.IsActive)
	if err != nil {
		status := http.StatusInternalServerError
		if err.Error() == "education not found" {
			status = http.StatusNotFound
		}
		c.JSON(status, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, item)
}

// DeleteEducation godoc
// @Summary Delete an education (Admin)
// @Description Delete an education by ID
// @Tags admin
// @Security ApiKeyAuth
// @Param id path string true "Education ID"
// @Success 200 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /admin/educations/{id} [delete]
func (h *EducationHandler) DeleteEducation(c *gin.Context) {
	id := c.Param("id")
	if err := h.educationService.DeleteEducation(id); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Education deleted successfully"})
}
