package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	deviceImportService "github.com/break/junhong_cmp_fiber/internal/service/device_import"
	"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 DeviceImportHandler struct {
	service *deviceImportService.Service
}

func NewDeviceImportHandler(service *deviceImportService.Service) *DeviceImportHandler {
	return &DeviceImportHandler{
		service: service,
	}
}

func (h *DeviceImportHandler) Import(c *fiber.Ctx) error {
	userType := middleware.GetUserTypeFromContext(c.UserContext())
	if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
		return errors.New(errors.CodeForbidden, "仅平台用户可导入设备")
	}

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

	if req.FileKey == "" {
		return errors.New(errors.CodeInvalidParam, "文件路径不能为空")
	}

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

	return response.Success(c, result)
}

// CreateAllocation 创建单列 CSV 设备批量分配任务。
// POST /api/admin/devices/import/allocations
func (h *DeviceImportHandler) CreateAllocation(c *fiber.Ctx) error {
	var req dto.CreateDeviceBatchAllocationRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}
	result, err := h.service.CreateBatchAllocationTask(c.UserContext(), &req)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

func (h *DeviceImportHandler) List(c *fiber.Ctx) error {
	userType := middleware.GetUserTypeFromContext(c.UserContext())
	if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
		return errors.New(errors.CodeForbidden, "仅平台用户可查看导入任务")
	}

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

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

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

func (h *DeviceImportHandler) GetByID(c *fiber.Ctx) error {
	userType := middleware.GetUserTypeFromContext(c.UserContext())
	if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
		return errors.New(errors.CodeForbidden, "仅平台用户可查看导入任务详情")
	}

	idStr := c.Params("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的任务ID")
	}

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

	return response.Success(c, result)
}
