package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	enterpriseDeviceService "github.com/break/junhong_cmp_fiber/internal/service/enterprise_device"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type EnterpriseDeviceHandler struct {
	service *enterpriseDeviceService.Service
}

func NewEnterpriseDeviceHandler(service *enterpriseDeviceService.Service) *EnterpriseDeviceHandler {
	return &EnterpriseDeviceHandler{service: service}
}

func (h *EnterpriseDeviceHandler) AllocateDevices(c *fiber.Ctx) error {
	enterpriseIDStr := c.Params("id")
	enterpriseID, err := strconv.ParseUint(enterpriseIDStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "企业ID格式错误")
	}

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

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

	return response.Success(c, result)
}

func (h *EnterpriseDeviceHandler) RecallDevices(c *fiber.Ctx) error {
	enterpriseIDStr := c.Params("id")
	enterpriseID, err := strconv.ParseUint(enterpriseIDStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "企业ID格式错误")
	}

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

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

	return response.Success(c, result)
}

func (h *EnterpriseDeviceHandler) ListDevices(c *fiber.Ctx) error {
	enterpriseIDStr := c.Params("id")
	enterpriseID, err := strconv.ParseUint(enterpriseIDStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "企业ID格式错误")
	}

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

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

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