package mysql

import (
	"context"
	"regexp"
	"testing"
	"time"

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

func TestGetLuckyGiftRechargeSnapshotUsesUTCNaturalDayWindows(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("create sqlmock: %v", err)
	}
	defer db.Close()
	mock.ExpectBegin()
	tx, err := db.Begin()
	if err != nil {
		t.Fatalf("begin transaction: %v", err)
	}
	defer tx.Rollback()

	now := time.Date(2026, 7, 12, 23, 59, 59, 999_000_000, time.UTC)
	sevenStart := time.Date(2026, 7, 6, 0, 0, 0, 0, time.UTC).UnixMilli()
	thirtyStart := time.Date(2026, 6, 13, 0, 0, 0, 0, time.UTC).UnixMilli()
	query := regexp.QuoteMeta(`
		SELECT
		  COALESCE(SUM(CASE WHEN created_at_ms >= ? THEN coin_amount ELSE 0 END), 0),
		  COALESCE(SUM(coin_amount), 0),
		  COALESCE(MAX(created_at_ms), 0)
		FROM wallet_recharge_records
		WHERE app_code = ? AND user_id = ?
		  AND created_at_ms >= ? AND created_at_ms < ?`)
	mock.ExpectQuery(query).
		WithArgs(sevenStart, "fami", int64(42), thirtyStart, now.UnixMilli()+1).
		WillReturnRows(sqlmock.NewRows([]string{"seven", "thirty", "last"}).AddRow(700, 3_000, now.Add(-time.Minute).UnixMilli()))

	repo := &Repository{db: db}
	snapshot, err := repo.getLuckyGiftRechargeSnapshot(appcode.WithContext(context.Background(), "fami"), tx, 42, "super_lucky", now.UnixMilli())
	if err != nil {
		t.Fatalf("get recharge snapshot: %v", err)
	}
	if snapshot.SevenDayCoins != 700 || snapshot.ThirtyDayCoins != 3_000 || snapshot.LastAtMS != now.Add(-time.Minute).UnixMilli() {
		t.Fatalf("unexpected snapshot: %+v", snapshot)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("sql expectations: %v", err)
	}
}

func TestGetLuckyGiftRechargeSnapshotSkipsNonLuckyGift(t *testing.T) {
	repo := &Repository{}
	snapshot, err := repo.getLuckyGiftRechargeSnapshot(context.Background(), nil, 42, "normal", 1)
	if err != nil {
		t.Fatalf("non-lucky snapshot: %v", err)
	}
	if snapshot != (luckyGiftRechargeSnapshot{}) {
		t.Fatalf("non-lucky gift must not expose recharge profile: %+v", snapshot)
	}
}
