package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/user-management-system/internal/service"
)

// CaptchaHandler handles captcha requests
type CaptchaHandler struct {
	captchaService *service.CaptchaService
}

// NewCaptchaHandler creates a new CaptchaHandler
func NewCaptchaHandler(captchaService *service.CaptchaService) *CaptchaHandler {
	return &CaptchaHandler{captchaService: captchaService}
}

func (h *CaptchaHandler) GenerateCaptcha(c *gin.Context) {
	result, err := h.captchaService.Generate(c.Request.Context())
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"captcha_id": result.CaptchaID,
		"image":      result.ImageData,
	})
}

func (h *CaptchaHandler) GetCaptchaImage(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "captcha image endpoint"})
}

func (h *CaptchaHandler) VerifyCaptcha(c *gin.Context) {
	var req struct {
		CaptchaID string `json:"captcha_id" binding:"required"`
		Answer    string `json:"answer" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if h.captchaService.Verify(c.Request.Context(), req.CaptchaID, req.Answer) {
		c.JSON(http.StatusOK, gin.H{"verified": true})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid captcha"})
	}
}
