package adminuser

import (
	"errors"
	"net/http"
	"strconv"
	"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 parsePagination(c *gin.Context) (int, int) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100
	}
	return page, pageSize
}

func (h *Handler) List(c *gin.Context) {
	page, pageSize := parsePagination(c)
	query := ListQuery{
		Keyword:             strings.TrimSpace(c.Query("keyword")),
		Status:              strings.TrimSpace(c.Query("status")),
		HasDepositFreeQuota: parseBoolQuery(c.Query("has_deposit_free_quota")),
	}
	result, err := h.service.List(c.Request.Context(), page, pageSize, query)
	if err != nil {
		writeAdminUserError(c, err)
		return
	}
	response.OK(c, result)
}

func parseBoolQuery(value string) bool {
	switch strings.ToLower(strings.TrimSpace(value)) {
	case "1", "true", "yes", "on":
		return true
	default:
		return false
	}
}

func (h *Handler) Freeze(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	userID, ok := parseID(c)
	if !ok {
		return
	}
	var req FreezeRequest
	_ = c.ShouldBindJSON(&req)
	item, err := h.service.Freeze(c.Request.Context(), adminID, userID, req, auditMeta(c))
	if err != nil {
		writeAdminUserError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Unfreeze(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	userID, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.Unfreeze(c.Request.Context(), adminID, userID, auditMeta(c))
	if err != nil {
		writeAdminUserError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) SetDepositFreeQuota(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	userID, ok := parseID(c)
	if !ok {
		return
	}
	var req DepositFreeQuotaRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "免押额度不正确")
		return
	}
	item, err := h.service.SetDepositFreeQuota(c.Request.Context(), adminID, userID, req, auditMeta(c))
	if err != nil {
		writeAdminUserError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) RevokeRealname(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	userID, ok := parseID(c)
	if !ok {
		return
	}
	var req RevokeRealnameRequest
	_ = c.ShouldBindJSON(&req)
	item, err := h.service.RevokeRealname(c.Request.Context(), adminID, userID, req, auditMeta(c))
	if err != nil {
		writeAdminUserError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) ManualRealname(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	userID, ok := parseID(c)
	if !ok {
		return
	}
	var req ManualRealnameRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "姓名和身份证号不能为空")
		return
	}
	item, err := h.service.ManualRealname(c.Request.Context(), adminID, userID, req, auditMeta(c))
	if err != nil {
		writeAdminUserError(c, err)
		return
	}
	response.OK(c, item)
}

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
}

func parseID(c *gin.Context) (uint64, bool) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		response.BadRequest(c, "ID 不正确")
		return 0, false
	}
	return id, true
}

func auditMeta(c *gin.Context) AuditMeta {
	return AuditMeta{
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		RequestID: middleware.GetRequestID(c),
	}
}

func writeAdminUserError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrInvalidUser):
		response.BadRequest(c, "用户不符合规则")
	case errors.Is(err, ErrInvalidRealnameInput):
		response.BadRequest(c, "姓名或身份证号格式不正确")
	case errors.Is(err, ErrRealnameAlreadyVerified):
		response.Error(c, http.StatusConflict, "realname_already_verified", "该用户已完成实名认证，如需修改请先撤销实名")
	case errors.Is(err, ErrRealnameNotRevocable):
		response.Error(c, http.StatusConflict, "realname_not_revocable", "该用户当前没有可撤销的实名信息")
	case IsNotFound(err):
		response.Error(c, http.StatusNotFound, "not_found", "用户不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "用户管理服务暂时不可用")
	}
}
