package admin

import (
	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	myCommissionService "github.com/break/junhong_cmp_fiber/internal/service/my_commission"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type MyCommissionHandler struct {
	service *myCommissionService.Service
}

func NewMyCommissionHandler(service *myCommissionService.Service) *MyCommissionHandler {
	return &MyCommissionHandler{service: service}
}

func (h *MyCommissionHandler) GetSummary(c *fiber.Ctx) error {
	result, err := h.service.GetCommissionSummary(c.UserContext())
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

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

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

	return response.Success(c, result)
}

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

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

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

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

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

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

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

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

	return response.Success(c, result)
}

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

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

	return response.Success(c, result)
}
