package repository

import (
	"testing"

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

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

	// 108 笔 Orders API 结果都已落库，但只有 2 笔带开发者净收。同步覆盖度必须仍为 108，
	// 金额估算则继续只覆盖净收有效的 2 笔，这正是 Google Merchant of Record 订单的线上边界。
	mock.ExpectQuery(`(?s)SELECT.*SUM\(CASE WHEN synced_at_ms > 0 THEN 1 ELSE 0 END\).*CASE WHEN paid_amount_micro > 0 AND paid_net_micro > 0.*WHERE app_code = \? AND bill_created_at_ms >= \? AND bill_created_at_ms < \?`).
		WithArgs("yumi", int64(1783872000000), int64(1783958400000)).
		WillReturnRows(sqlmock.NewRows([]string{"synced_count", "covered_usd_minor", "fee_usd_minor", "tax_usd_minor", "net_usd_minor"}).
			AddRow(108, 4200, 630, 210, 3360))

	stats, err := store.LegacyGooglePaidStatsByBillTime(" YUMI ", 1783872000000, 1783958400000)
	if err != nil {
		t.Fatalf("load legacy google paid stats failed: %v", err)
	}
	if stats.SyncedCount != 108 {
		t.Fatalf("synced count must use synced_at_ms instead of net revenue: %+v", stats)
	}
	if stats.CoveredUSDMinor != 4200 || stats.EstFeeUSDMinor != 630 || stats.EstTaxUSDMinor != 210 || stats.EstNetUSDMinor != 3360 {
		t.Fatalf("settlement estimates mismatch: %+v", stats)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("sql expectations mismatch: %v", err)
	}
}
