package wallet

import (
	"errors"
	"strconv"

	"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) Balance(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	account, err := h.service.Account(userID)
	if err != nil {
		writeWalletError(c, err)
		return
	}
	response.OK(c, account)
}

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) Ledger(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	page, pageSize := parsePagination(c)
	result, err := h.service.Ledger(userID, page, pageSize)
	if err != nil {
		writeWalletError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) Recharge(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	var req RechargeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "充值金额不正确")
		return
	}
	account, err := h.service.Recharge(userID, req)
	if err != nil {
		writeWalletError(c, err)
		return
	}
	response.OK(c, account)
}

func (h *Handler) Withdraw(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	var req WithdrawRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "提现金额不正确")
		return
	}
	account, err := h.service.Withdraw(userID, req)
	if err != nil {
		writeWalletError(c, err)
		return
	}
	response.OK(c, account)
}

func (h *Handler) AdminLedger(c *gin.Context) {
	query, ok := parseAdminLedgerQuery(c)
	if !ok {
		return
	}
	result, err := h.service.AdminLedger(query)
	if err != nil {
		writeWalletError(c, err)
		return
	}
	response.OK(c, result)
}

func parseAdminLedgerQuery(c *gin.Context) (AdminLedgerQuery, bool) {
	var query AdminLedgerQuery
	if raw := c.Query("user_id"); raw != "" {
		value, err := strconv.ParseUint(raw, 10, 64)
		if err != nil || value == 0 {
			response.BadRequest(c, "用户 ID 不正确")
			return query, false
		}
		query.UserID = value
	}
	if raw := c.Query("order_id"); raw != "" {
		value, err := strconv.ParseUint(raw, 10, 64)
		if err != nil || value == 0 {
			response.BadRequest(c, "订单 ID 不正确")
			return query, false
		}
		query.OrderID = value
	}
	query.BizType = c.Query("biz_type")
	page, pageSize := parsePagination(c)
	query.Page = page
	query.PageSize = pageSize
	return query, true
}

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

func writeWalletError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrInvalidAmount):
		response.BadRequest(c, "充值金额不正确")
	case errors.Is(err, ErrInsufficientBalance):
		response.Error(c, 409, "insufficient_balance", "钱包余额不足")
	case errors.Is(err, ErrRechargeDisabled):
		response.Error(c, 410, "wallet_recharge_disabled", "钱包充值已关闭")
	case errors.Is(err, ErrFeaturePending):
		response.Error(c, 501, "feature_pending", "提现功能待开发")
	default:
		response.ServiceUnavailable(c, "钱包服务暂时不可用")
	}
}
