package adminauth

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

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

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

const (
	adminAccessCookieName    = middleware.AdminAccessCookieName
	adminRefreshCookieName   = "hfb_admin_refresh"
	adminRefreshCookieMaxAge = 14 * 24 * 60 * 60
)

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(c.Request.Context())
	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(c.Request.Context(), strings.TrimSpace(req.Username), req.Password, strings.TrimSpace(req.CaptchaID), strings.TrimSpace(req.CaptchaCode), c.ClientIP())
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	setAdminAuthCookies(c, result.Tokens)
	response.OK(c, gin.H{"admin": result.Admin})
}

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(c.Request.Context(), adminID)
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	response.OK(c, admin)
}

func (h *Handler) Logout(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	if err := h.service.Logout(c.Request.Context(), adminID); err != nil {
		writeAdminAuthError(c, err)
		return
	}
	clearAdminAuthCookies(c)
	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(c.Request.Context(), 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"`
}

func (h *Handler) Refresh(c *gin.Context) {
	var req AdminRefreshRequest
	if c.Request.Body != nil && c.Request.ContentLength != 0 {
		if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
			response.BadRequest(c, "refresh_token 格式不正确")
			return
		}
	}
	refreshToken := strings.TrimSpace(req.RefreshToken)
	if refreshToken == "" {
		if cookieValue, err := c.Cookie(adminRefreshCookieName); err == nil {
			refreshToken = strings.TrimSpace(cookieValue)
		}
	}
	if refreshToken == "" {
		response.BadRequest(c, "refresh_token 不能为空")
		return
	}
	tokens, err := h.service.Refresh(c.Request.Context(), refreshToken)
	if err != nil {
		writeAdminAuthError(c, err)
		return
	}
	setAdminAuthCookies(c, *tokens)
	response.OK(c, gin.H{"refreshed": true, "expires_in": tokens.ExpiresInSeconds})
}

func setAdminAuthCookies(c *gin.Context, tokens auth.TokenPair) {
	secure := isHTTPSRequest(c)
	httpOnly := true
	sameSite := http.SameSiteStrictMode
	c.SetSameSite(sameSite)
	c.SetCookie(adminAccessCookieName, tokens.AccessToken, int(tokens.ExpiresInSeconds), "/api/admin", "", secure, httpOnly)
	c.SetCookie(adminRefreshCookieName, tokens.RefreshToken, adminRefreshCookieMaxAge, "/api/admin/auth/refresh", "", secure, httpOnly)
}

func clearAdminAuthCookies(c *gin.Context) {
	secure := isHTTPSRequest(c)
	c.SetSameSite(http.SameSiteStrictMode)
	c.SetCookie(adminAccessCookieName, "", -1, "/api/admin", "", secure, true)
	c.SetCookie(adminRefreshCookieName, "", -1, "/api/admin/auth/refresh", "", secure, true)
}

func isHTTPSRequest(c *gin.Context) bool {
	if c.Request.TLS != nil {
		return true
	}
	return strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")
}

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, ErrLoginLocked):
		response.Error(c, http.StatusTooManyRequests, "login_locked", "登录失败次数过多，请稍后再试")
	case errors.Is(err, ErrAdminDisabled):
		response.Error(c, http.StatusForbidden, "admin_disabled", "管理员已禁用")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "后台认证服务暂时不可用")
	}
}
