package admin

import (
	"strconv"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	commissionWithdrawalService "github.com/break/junhong_cmp_fiber/internal/service/commission_withdrawal"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

// CommissionWithdrawalHandler 提现申请管理处理器
type CommissionWithdrawalHandler struct {
	service   *commissionWithdrawalService.Service
	validator *validator.Validate
}

// NewCommissionWithdrawalHandler 创建提现申请管理处理器
func NewCommissionWithdrawalHandler(service *commissionWithdrawalService.Service, validator *validator.Validate) *CommissionWithdrawalHandler {
	return &CommissionWithdrawalHandler{service: service, validator: validator}
}

func (h *CommissionWithdrawalHandler) ListWithdrawalRequests(c *fiber.Ctx) error {
	var req dto.WithdrawalRequestListReq
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	result, err := h.service.ListWithdrawalRequests(c.UserContext(), &req)
	if err != nil {
		return err
	}

	return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
}

func (h *CommissionWithdrawalHandler) ApproveWithdrawal(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的提现申请ID")
	}

	var req dto.ApproveWithdrawalReq
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	result, err := h.service.Approve(c.UserContext(), uint(id), &req)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

func (h *CommissionWithdrawalHandler) RejectWithdrawal(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的提现申请ID")
	}

	var req dto.RejectWithdrawalReq
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}
	if err := h.validator.Struct(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}

	result, err := h.service.Reject(c.UserContext(), uint(id), &req)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}
