package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	enterpriseCardService "github.com/break/junhong_cmp_fiber/internal/service/enterprise_card"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type EnterpriseCardHandler struct {
	service *enterpriseCardService.Service
}

func NewEnterpriseCardHandler(service *enterpriseCardService.Service) *EnterpriseCardHandler {
	return &EnterpriseCardHandler{service: service}
}

func (h *EnterpriseCardHandler) AllocateCards(c *fiber.Ctx) error {
	idStr := c.Params("id")
	enterpriseID, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的企业ID")
	}

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

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

	return response.Success(c, result)
}

func (h *EnterpriseCardHandler) RecallCards(c *fiber.Ctx) error {
	idStr := c.Params("id")
	enterpriseID, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的企业ID")
	}

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

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

	return response.Success(c, result)
}

func (h *EnterpriseCardHandler) ListCards(c *fiber.Ctx) error {
	idStr := c.Params("id")
	enterpriseID, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的企业ID")
	}

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

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

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