package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	shopService "github.com/break/junhong_cmp_fiber/internal/service/shop"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type ShopRoleHandler struct {
	service *shopService.Service
}

func NewShopRoleHandler(service *shopService.Service) *ShopRoleHandler {
	return &ShopRoleHandler{service: service}
}

func (h *ShopRoleHandler) AssignShopRoles(c *fiber.Ctx) error {
	shopIDStr := c.Params("shop_id")
	shopID, err := strconv.ParseUint(shopIDStr, 10, 32)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "店铺ID格式错误")
	}

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

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

	return response.Success(c, result)
}

func (h *ShopRoleHandler) GetShopRoles(c *fiber.Ctx) error {
	shopIDStr := c.Params("shop_id")
	shopID, err := strconv.ParseUint(shopIDStr, 10, 32)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "店铺ID格式错误")
	}

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

	return response.Success(c, result)
}

func (h *ShopRoleHandler) DeleteShopRole(c *fiber.Ctx) error {
	shopIDStr := c.Params("shop_id")
	shopID, err := strconv.ParseUint(shopIDStr, 10, 32)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "店铺ID格式错误")
	}

	roleIDStr := c.Params("role_id")
	roleID, err := strconv.ParseUint(roleIDStr, 10, 32)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "角色ID格式错误")
	}

	if err := h.service.DeleteShopRole(c.UserContext(), uint(shopID), uint(roleID)); err != nil {
		return err
	}

	return response.Success(c, nil)
}
