package postgres

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

// AgentWalletTransactionStore 代理钱包交易记录数据访问层
type AgentWalletTransactionStore struct {
	db    *gorm.DB
	redis *redis.Client
}

// NewAgentWalletTransactionStore 创建代理钱包交易记录 Store
func NewAgentWalletTransactionStore(db *gorm.DB, redis *redis.Client) *AgentWalletTransactionStore {
	return &AgentWalletTransactionStore{
		db:    db,
		redis: redis,
	}
}

// AgentWalletTransactionListFilters 主钱包流水过滤条件
type AgentWalletTransactionListFilters struct {
	// TransactionType 按交易类型过滤，空字符串表示不过滤
	TransactionType string
	// StartDate 开始日期，格式 YYYY-MM-DD
	StartDate string
	// EndDate 结束日期，格式 YYYY-MM-DD
	EndDate string
	// AssetIdentifier 资产标识精确匹配（ICCID 或设备虚拟号），空字符串表示不过滤
	AssetIdentifier string
}

// CreateWithTx 创建代理钱包交易记录（带事务）
func (s *AgentWalletTransactionStore) CreateWithTx(ctx context.Context, tx *gorm.DB, transaction *model.AgentWalletTransaction) error {
	return tx.WithContext(ctx).Create(transaction).Error
}

// ListByWalletIDWithFilters 按钱包ID查询交易记录（支持分页和过滤）
// 按 created_at DESC 排序
func (s *AgentWalletTransactionStore) ListByWalletIDWithFilters(ctx context.Context, walletID uint, offset, limit int, filters *AgentWalletTransactionListFilters) ([]*model.AgentWalletTransaction, error) {
	var transactions []*model.AgentWalletTransaction
	query := s.db.WithContext(ctx).Where("agent_wallet_id = ?", walletID)
	query = applyWalletTransactionFilters(query, filters)
	err := query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&transactions).Error
	if err != nil {
		return nil, err
	}
	return transactions, nil
}

// CountByWalletID 统计指定钱包的交易记录数量（支持过滤）
func (s *AgentWalletTransactionStore) CountByWalletID(ctx context.Context, walletID uint, filters *AgentWalletTransactionListFilters) (int64, error) {
	var count int64
	query := s.db.WithContext(ctx).Model(&model.AgentWalletTransaction{}).Where("agent_wallet_id = ?", walletID)
	query = applyWalletTransactionFilters(query, filters)
	err := query.Count(&count).Error
	return count, err
}

// ListByWalletID 按钱包查询交易记录（支持分页）
func (s *AgentWalletTransactionStore) ListByWalletID(ctx context.Context, walletID uint, offset, limit int) ([]*model.AgentWalletTransaction, error) {
	var transactions []*model.AgentWalletTransaction
	query := s.db.WithContext(ctx).Where("agent_wallet_id = ?", walletID)
	err := query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&transactions).Error
	if err != nil {
		return nil, err
	}
	return transactions, nil
}

// GetByReference 根据关联业务查询交易记录
func (s *AgentWalletTransactionStore) GetByReference(ctx context.Context, referenceType string, referenceID uint) (*model.AgentWalletTransaction, error) {
	var transaction model.AgentWalletTransaction
	query := s.db.WithContext(ctx).Where("reference_type = ? AND reference_id = ?", referenceType, referenceID)
	err := query.First(&transaction).Error
	if err != nil {
		return nil, err
	}
	return &transaction, nil
}

// applyWalletTransactionFilters 应用过滤条件到查询
func applyWalletTransactionFilters(query *gorm.DB, filters *AgentWalletTransactionListFilters) *gorm.DB {
	if filters == nil {
		return query
	}
	if filters.TransactionType != "" {
		query = query.Where("transaction_type = ?", filters.TransactionType)
	}
	if filters.StartDate != "" {
		query = query.Where("created_at >= ?", filters.StartDate+" 00:00:00")
	}
	if filters.EndDate != "" {
		query = query.Where("created_at <= ?", filters.EndDate+" 23:59:59")
	}
	if filters.AssetIdentifier != "" {
		query = query.Where("asset_identifier = ?", filters.AssetIdentifier)
	}
	return query
}
