package mysql

import (
	"context"
	"fmt"

	"hyapp/pkg/appcode"
	"hyapp/services/wallet-service/internal/domain/ledger"
)

const maxBatchRechargeStatsUsers = 500

// BatchGetUserRechargeStats 批量读取 owner 维护的累计表；输入先去重，避免 IN 参数和返回行无意义膨胀。
func (r *Repository) BatchGetUserRechargeStats(ctx context.Context, userIDs []int64) ([]ledger.UserRechargeStats, error) {
	userIDs = uniquePositiveUserIDs(userIDs)
	if len(userIDs) == 0 {
		return []ledger.UserRechargeStats{}, nil
	}
	if len(userIDs) > maxBatchRechargeStatsUsers {
		return nil, fmt.Errorf("too many user ids: %d", len(userIDs))
	}
	args := make([]any, 0, len(userIDs)+1)
	args = append(args, appcode.FromContext(ctx))
	for _, userID := range userIDs {
		args = append(args, userID)
	}
	rows, err := r.db.QueryContext(ctx, `
		SELECT user_id, recharge_count, total_coin_amount, total_usd_minor_amount,
		       first_recharged_at_ms, updated_at_ms
		FROM wallet_user_recharge_stats
		WHERE app_code = ? AND user_id IN (`+placeholders(len(userIDs))+`)
		ORDER BY user_id ASC`, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	items := make([]ledger.UserRechargeStats, 0, len(userIDs))
	for rows.Next() {
		var item ledger.UserRechargeStats
		if err := rows.Scan(
			&item.UserID,
			&item.RechargeCount,
			&item.TotalCoinAmount,
			&item.TotalUSDMinorAmount,
			&item.FirstRechargedAtMS,
			&item.UpdatedAtMS,
		); err != nil {
			return nil, err
		}
		items = append(items, item)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

func uniquePositiveUserIDs(values []int64) []int64 {
	seen := make(map[int64]struct{}, len(values))
	result := make([]int64, 0, len(values))
	for _, value := range values {
		if value <= 0 {
			continue
		}
		if _, ok := seen[value]; ok {
			continue
		}
		seen[value] = struct{}{}
		result = append(result, value)
	}
	return result
}
