package admin

import (
	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	assetSvc "github.com/break/junhong_cmp_fiber/internal/service/asset"
	assetWalletSvc "github.com/break/junhong_cmp_fiber/internal/service/asset_wallet"
	"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"
)

// AssetWalletHandler 资产钱包处理器
// 提供管理端资产（卡/设备）钱包概况和流水查询接口
type AssetWalletHandler struct {
	service      *assetWalletSvc.Service
	assetService *assetSvc.Service
}

// NewAssetWalletHandler 创建资产钱包处理器
func NewAssetWalletHandler(svc *assetWalletSvc.Service) *AssetWalletHandler {
	return &AssetWalletHandler{service: svc}
}

// SetAssetService 注入资产解析服务（用于通过标识符解析资产类型和ID）
func (h *AssetWalletHandler) SetAssetService(svc *assetSvc.Service) {
	h.assetService = svc
}

// GetWallet 查询资产钱包概况
// GET /api/admin/assets/:identifier/wallet
func (h *AssetWalletHandler) GetWallet(c *fiber.Ctx) error {
	userType := middleware.GetUserTypeFromContext(c.UserContext())
	if userType == constants.UserTypeEnterprise {
		return errors.New(errors.CodeForbidden, "企业账号无权查看钱包信息")
	}

	identifier := c.Params("identifier")
	if identifier == "" {
		return errors.New(errors.CodeInvalidParam, "标识符不能为空")
	}

	if h.assetService == nil {
		return errors.New(errors.CodeInternalError, "资产服务未配置")
	}

	asset, err := h.assetService.Resolve(c.UserContext(), identifier, false)
	if err != nil {
		return err
	}

	result, err := h.service.GetWallet(c.UserContext(), asset.AssetType, asset.AssetID)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

// ListTransactions 查询资产钱包流水列表
// GET /api/admin/assets/:identifier/wallet/transactions
func (h *AssetWalletHandler) ListTransactions(c *fiber.Ctx) error {
	userType := middleware.GetUserTypeFromContext(c.UserContext())
	if userType == constants.UserTypeEnterprise {
		return errors.New(errors.CodeForbidden, "企业账号无权查看钱包信息")
	}

	identifier := c.Params("identifier")
	if identifier == "" {
		return errors.New(errors.CodeInvalidParam, "标识符不能为空")
	}

	if h.assetService == nil {
		return errors.New(errors.CodeInternalError, "资产服务未配置")
	}

	asset, err := h.assetService.Resolve(c.UserContext(), identifier, false)
	if err != nil {
		return err
	}

	var req dto.AssetWalletTransactionListRequest
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}

	if req.PageSize > 100 {
		return errors.New(errors.CodeInvalidParam, "每页数量不能超过100")
	}

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

	return response.Success(c, result)
}
