package repository

import (
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
)

func TestCoinSellerRechargeOrderStatsAggregatesVerifiedAndGrantedOverlap(t *testing.T) {
	store, mock, closeStore := newRepositorySQLMock(t)
	defer closeStore()

	mock.ExpectQuery("provider_code.*=").
		WillReturnRows(sqlmock.NewRows([]string{
			"verified_usd_minor",
			"verified_coin_amount",
			"verified_count",
			"granted_usd_minor",
			"granted_coin_amount",
			"granted_count",
		}).AddRow(int64(3_000), int64(30_000), int64(3), int64(2_000), int64(20_000), int64(2)))
	mock.ExpectQuery("DATE_FORMAT").
		WillReturnRows(sqlmock.NewRows([]string{"date", "count", "usd_minor", "coin_amount"}).
			AddRow("2026-07-08", int64(1), int64(1_000), int64(10_000)).
			AddRow("2026-07-09", int64(2), int64(2_000), int64(20_000)))
	mock.ExpectQuery("DATE_FORMAT").
		WillReturnRows(sqlmock.NewRows([]string{"date", "count", "usd_minor", "coin_amount"}).
			AddRow("2026-07-09", int64(2), int64(2_000), int64(20_000)))
	mock.ExpectQuery("target_region_id AS region_id").
		WillReturnRows(sqlmock.NewRows([]string{"region_id", "country_id", "count", "usd_minor", "coin_amount"}).
			AddRow(int64(101), int64(91), int64(3), int64(3_000), int64(30_000)))
	mock.ExpectQuery("target_region_id AS region_id").
		WillReturnRows(sqlmock.NewRows([]string{"region_id", "country_id", "count", "usd_minor", "coin_amount"}).
			AddRow(int64(101), int64(91), int64(2), int64(2_000), int64(20_000)))

	stats, err := store.CoinSellerRechargeOrderStats(CoinSellerRechargeOrderStatsOptions{
		AppCode:        "lalu",
		RechargeSource: CoinSellerRechargeSourceUSDT,
		RegionID:       101,
		TargetUserID:   9001,
		Keyword:        "merchant-1",
		CreatedFromMS:  1_783_468_800_000,
		CreatedToMS:    1_783_555_200_000,
	})
	if err != nil {
		t.Fatalf("CoinSellerRechargeOrderStats failed: %v", err)
	}
	if stats.VerifiedCount != 3 || stats.VerifiedUSDMinor != 3_000 || stats.VerifiedCoinAmount != 30_000 {
		t.Fatalf("verified totals mismatch: %+v", stats)
	}
	if stats.GrantedCount != 2 || stats.GrantedUSDMinor != 2_000 || stats.GrantedCoinAmount != 20_000 {
		t.Fatalf("granted totals mismatch: %+v", stats)
	}
	if stats.VerifiedDaily["2026-07-08"].USDMinor != 1_000 || stats.GrantedDaily["2026-07-09"].CoinAmount != 20_000 {
		t.Fatalf("daily stats mismatch: %+v", stats)
	}
	if len(stats.VerifiedRegionBuckets) != 1 || stats.VerifiedRegionBuckets[0].RegionID != 101 || stats.VerifiedRegionBuckets[0].CountryID != 91 {
		t.Fatalf("region stats mismatch: %+v", stats.VerifiedRegionBuckets)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("sql expectations mismatch: %v", err)
	}
}
