package adminauth

import (
	"errors"
	"net/http"
	"strings"

	"hfb_sys/backend/internal/middleware"
	"hfb_sys/backend/pkg/response"

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

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

func (h *Handler) Captcha(c *gin.Context) {
	item, err := h.service.Captcha()
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "用户名、密码和验证码不能为空")
		return
	}
	result, err := h.service.Login(strings.TrimSpace(req.Username), req.Password, strings.TrimSpace(req.CaptchaID), strings.TrimSpace(req.CaptchaCode))
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) Me(c *gin.Context) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	adminID, ok := value.(uint64)
	if !ok {
		response.Unauthorized(c, "管理员上下文无效")
		return
	}
	admin, err := h.service.Me(adminID)
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	response.OK(c, admin)
}

func (h *Handler) Logout(c *gin.Context) {
	response.OK(c, gin.H{"logged_out": true})
}

func (h *Handler) UpdateSupportStatus(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	var req UpdateSupportStatusRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "状态值无效，必须是 online、offline 或 busy")
		return
	}
	if err := h.service.UpdateSupportStatus(adminID, req.Status); err != nil {
		writeAdminAuthError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true, "support_status": req.Status})
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		return 0, false
	}
	adminID, ok := value.(uint64)
	return adminID, ok
}

type AdminRefreshRequest struct {
	RefreshToken string `json:"refresh_token" binding:"required"`
}

func (h *Handler) Refresh(c *gin.Context) {
	var req AdminRefreshRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "refresh_token 不能为空")
		return
	}
	tokens, err := h.service.Refresh(req.RefreshToken)
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	response.OK(c, tokens)
}

func writeAdminAuthError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrInvalidRefreshToken):
		response.Unauthorized(c, "刷新令牌无效或已过期")
	case errors.Is(err, ErrInvalidCredential):
		response.BadRequest(c, "用户名或密码错误")
	case errors.Is(err, ErrCaptchaInvalid):
		response.BadRequest(c, "验证码错误或已过期")
	case errors.Is(err, ErrAdminDisabled):
		response.Error(c, http.StatusForbidden, "admin_disabled", "管理员已禁用")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "后台认证服务暂时不可用")
	}
}
