package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	shopCommissionService "github.com/break/junhong_cmp_fiber/internal/service/shop_commission"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type ShopCommissionHandler struct {
	service *shopCommissionService.Service
}

func NewShopCommissionHandler(service *shopCommissionService.Service) *ShopCommissionHandler {
	return &ShopCommissionHandler{service: service}
}

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

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

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

func (h *ShopCommissionHandler) ListWithdrawalRequests(c *fiber.Ctx) error {
	shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的店铺 ID")
	}

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

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

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

func (h *ShopCommissionHandler) ListCommissionRecords(c *fiber.Ctx) error {
	shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的店铺 ID")
	}

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

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

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