package admin

import (
	"context"
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

// AssetLifecycleService 资产生命周期服务接口
type AssetLifecycleService interface {
	// DeactivateIotCard 停用 IoT 卡
	DeactivateIotCard(ctx context.Context, id uint) error
	// DeactivateDevice 停用设备
	DeactivateDevice(ctx context.Context, id uint) error
}

// AssetLifecycleHandler 资产生命周期处理器
type AssetLifecycleHandler struct {
	service AssetLifecycleService
}

// NewAssetLifecycleHandler 创建资产生命周期处理器
func NewAssetLifecycleHandler(service AssetLifecycleService) *AssetLifecycleHandler {
	return &AssetLifecycleHandler{service: service}
}

// DeactivateIotCard 手动停用 IoT 卡
// PATCH /api/admin/iot-cards/:id/deactivate
func (h *AssetLifecycleHandler) DeactivateIotCard(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的卡ID")
	}

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

	return response.Success(c, nil)
}

// DeactivateDevice 手动停用设备
// PATCH /api/admin/devices/:id/deactivate
func (h *AssetLifecycleHandler) DeactivateDevice(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的设备ID")
	}

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

	return response.Success(c, nil)
}
