package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	invalidateSvc "github.com/break/junhong_cmp_fiber/internal/service/order_package_invalidate"
	"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"
)

// OrderPackageInvalidateHandler 订单套餐批量失效任务 Handler
type OrderPackageInvalidateHandler struct {
	service *invalidateSvc.Service
}

// NewOrderPackageInvalidateHandler 创建 Handler 实例
func NewOrderPackageInvalidateHandler(service *invalidateSvc.Service) *OrderPackageInvalidateHandler {
	return &OrderPackageInvalidateHandler{service: service}
}

// Create 创建批量失效订单套餐任务
// POST /api/admin/order-package-invalidate-tasks
func (h *OrderPackageInvalidateHandler) Create(c *fiber.Ctx) error {
	userType := middleware.GetUserTypeFromContext(c.UserContext())
	if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
		return errors.New(errors.CodeForbidden, "仅平台用户可创建套餐失效任务")
	}

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

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

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

	return response.Success(c, result)
}

// List 查询批量失效任务列表
// GET /api/admin/order-package-invalidate-tasks
func (h *OrderPackageInvalidateHandler) 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.ListOrderPackageInvalidateTaskRequest
	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)
}

// GetByID 查询批量失效任务详情
// GET /api/admin/order-package-invalidate-tasks/:id
func (h *OrderPackageInvalidateHandler) 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)
}
