package mysql

import (
	"context"
	"regexp"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
	"hyapp/pkg/appcode"
)

func TestBatchGetUserRechargeStatsUsesAggregateTableAndDeduplicatesIDs(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("create sqlmock: %v", err)
	}
	defer db.Close()

	mock.ExpectQuery(regexp.QuoteMeta(`
		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 (?,?)
		ORDER BY user_id ASC`)).
		WithArgs("lalu", int64(1001), int64(1002)).
		WillReturnRows(sqlmock.NewRows([]string{
			"user_id", "recharge_count", "total_coin_amount", "total_usd_minor_amount", "first_recharged_at_ms", "updated_at_ms",
		}).AddRow(int64(1001), int64(3), int64(9000), int64(1250), int64(1700000000000), int64(1700000005000)))

	repo := &Repository{db: db}
	items, err := repo.BatchGetUserRechargeStats(appcode.WithContext(context.Background(), "lalu"), []int64{1001, 0, 1002, 1001})
	if err != nil {
		t.Fatalf("BatchGetUserRechargeStats failed: %v", err)
	}
	if len(items) != 1 || items[0].UserID != 1001 || items[0].TotalUSDMinorAmount != 1250 || items[0].RechargeCount != 3 {
		t.Fatalf("unexpected recharge stats: %+v", items)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("unmet sql expectations: %v", err)
	}
}
