package handlers

import (
	"net/http"
	"strings"

	"gauth-central/internal/services"

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

type KnowledgeHandler struct {
	knowledgeService *services.KnowledgeService
}

func NewKnowledgeHandler(knowledgeService *services.KnowledgeService) *KnowledgeHandler {
	return &KnowledgeHandler{knowledgeService: knowledgeService}
}

type CreateKnowledgeRequest struct {
	Title    string `json:"title"`
	ResumeID string `json:"resume_id"`
	IsActive *bool  `json:"is_active"`
}

type UpdateKnowledgeRequest struct {
	Title    *string `json:"title"`
	ResumeID *string `json:"resume_id"`
	IsActive *bool   `json:"is_active"`
}

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

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

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

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

	req.Title = strings.TrimSpace(req.Title)
	if req.Title == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "title is 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.knowledgeService.CreateKnowledge(req.Title, resumeUUID, isActive)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, item)
}

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

	if req.Title != nil {
		trimmed := strings.TrimSpace(*req.Title)
		req.Title = &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.knowledgeService.UpdateKnowledge(id, req.Title, resumeUUIDPtr, req.IsActive)
	if err != nil {
		status := http.StatusInternalServerError
		if err.Error() == "knowledge not found" {
			status = http.StatusNotFound
		}
		c.JSON(status, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, item)
}

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