package admin

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

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	assetAllocationRecordService "github.com/break/junhong_cmp_fiber/internal/service/asset_allocation_record"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/middleware"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type AssetAllocationRecordHandler struct {
	service *assetAllocationRecordService.Service
}

func NewAssetAllocationRecordHandler(service *assetAllocationRecordService.Service) *AssetAllocationRecordHandler {
	return &AssetAllocationRecordHandler{service: service}
}

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

	ctx := c.UserContext()
	userType := middleware.GetUserTypeFromContext(ctx)
	var userShopID *uint
	if userType == constants.UserTypeAgent {
		shopID := middleware.GetShopIDFromContext(ctx)
		if shopID > 0 {
			userShopID = &shopID
		}
	}

	result, err := h.service.List(ctx, &req, userShopID)
	if err != nil {
		return err
	}

	return response.SuccessWithPagination(c, result.List, result.Total, result.Page, result.PageSize)
}

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

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

	return response.Success(c, result)
}
