package withdrawal

import (
	"hfb_sys/backend/pkg/response"
	"strconv"

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

type Handler struct {
	service *Service
}

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

// ========== 用户端接口 ==========

func (h *Handler) Create(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	var req CreateWithdrawalRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误")
		return
	}

	withdrawal, err := h.service.Create(c.Request.Context(), userID, req)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, withdrawal)
}

func (h *Handler) List(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	result, err := h.service.List(c.Request.Context(), userID, page, pageSize)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, result)
}

func (h *Handler) FindByID(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	id, ok := parseID(c)
	if !ok {
		return
	}

	withdrawal, err := h.service.FindByID(c.Request.Context(), userID, id)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, withdrawal)
}

func (h *Handler) Cancel(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	id, ok := parseID(c)
	if !ok {
		return
	}

	if err := h.service.Cancel(c.Request.Context(), userID, id); err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, gin.H{"cancelled": true})
}

// ========== 管理员端接口 ==========

func (h *Handler) AdminList(c *gin.Context) {
	var query AdminListQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		query.Page = 1
		query.Size = 20
	}

	result, err := h.service.AdminList(c.Request.Context(), query)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, result)
}

func (h *Handler) AdminFindByID(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}

	withdrawal, err := h.service.AdminFindByID(c.Request.Context(), id)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, withdrawal)
}

func (h *Handler) Review(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}

	id, ok := parseID(c)
	if !ok {
		return
	}

	var req ReviewWithdrawalRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误")
		return
	}

	withdrawal, err := h.service.Review(c.Request.Context(), adminID, id, req)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, withdrawal)
}

func (h *Handler) ConfirmPayment(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}

	id, ok := parseID(c)
	if !ok {
		return
	}

	var req ConfirmPaymentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误")
		return
	}

	withdrawal, err := h.service.ConfirmPayment(c.Request.Context(), adminID, id, req)
	if err != nil {
		writeError(c, err)
		return
	}

	response.OK(c, withdrawal)
}

// ========== 辅助函数 ==========

func currentUserID(c *gin.Context) (uint64, bool) {
	val, exists := c.Get("user_id")
	if !exists {
		return 0, false
	}
	userID, ok := val.(uint64)
	return userID, ok
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	val, exists := c.Get("admin_id")
	if !exists {
		return 0, false
	}
	adminID, ok := val.(uint64)
	return adminID, ok
}

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

func writeError(c *gin.Context, err error) {
	switch err {
	case ErrWithdrawalNotFound:
		response.NotFound(c, "提现申请不存在")
	case ErrInvalidAmount:
		response.BadRequest(c, "提现金额无效")
	case ErrInsufficientBalance:
		response.BadRequest(c, "余额不足")
	case ErrMinWithdrawalAmount:
		response.BadRequest(c, "提现金额低于最小限额")
	case ErrMaxWithdrawalAmount:
		response.BadRequest(c, "提现金额超过最大限额")
	case ErrWithdrawalLocked:
		response.BadRequest(c, "提现申请状态已锁定，无法操作")
	case ErrInvalidReviewAction:
		response.BadRequest(c, "审核参数无效")
	case ErrUnauthorized:
		response.Unauthorized(c, "无权限操作")
	default:
		response.InternalServerError(c, "操作失败")
	}
}
