package admin

import (
	"strconv"

	"github.com/bytedance/sonic"
	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	batchAllocationService "github.com/break/junhong_cmp_fiber/internal/service/shop_package_batch_allocation"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type ShopPackageBatchAllocationHandler struct {
	service *batchAllocationService.Service
}

func NewShopPackageBatchAllocationHandler(service *batchAllocationService.Service) *ShopPackageBatchAllocationHandler {
	return &ShopPackageBatchAllocationHandler{service: service}
}

// BatchAllocate 批量分配套餐
// POST /api/admin/shop-package-allocations/batch
func (h *ShopPackageBatchAllocationHandler) BatchAllocate(c *fiber.Ctx) error {
	var req dto.BatchAllocatePackagesRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}
	req.ExpiryBaseOverrideSet = hasJSONField(c.Body(), "expiry_base_override")

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

	return response.Success(c, result)
}

// UpdateExpiryBase 修改套餐分配生效条件覆盖。
// PATCH /api/admin/shop-package-allocations/:id/expiry-base
func (h *ShopPackageBatchAllocationHandler) UpdateExpiryBase(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	var req dto.UpdateAllocationExpiryBaseRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	req.ExpiryBaseOverrideSet = hasJSONField(c.Body(), "expiry_base_override")
	result, err := h.service.UpdateExpiryBase(c.UserContext(), uint(id), &req)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

func hasJSONField(body []byte, field string) bool {
	var object map[string]any
	if err := sonic.Unmarshal(body, &object); err != nil {
		return false
	}
	_, ok := object[field]
	return ok
}
