package payment

import (
	"context"
	"testing"
	"time"

	"hyapp-admin-server/internal/config"
)

type fakeLegacyGooglePaidSyncSource struct {
	pending []string
	results []googleRechargePaidDTO
}

func (s *fakeLegacyGooglePaidSyncSource) AppCode() string              { return "yumi" }
func (s *fakeLegacyGooglePaidSyncSource) SupportsGooglePaidSync() bool { return true }
func (s *fakeLegacyGooglePaidSyncSource) ListPendingGooglePaidTransactionIDs(context.Context, int) ([]string, error) {
	return append([]string(nil), s.pending...), nil
}
func (s *fakeLegacyGooglePaidSyncSource) RefreshGooglePaidDetails(context.Context, []string) ([]googleRechargePaidDTO, error) {
	return append([]googleRechargePaidDTO(nil), s.results...), nil
}

type fakeLegacyGooglePaidAttemptStore struct {
	cleared []string
	failed  []string
}

func (s *fakeLegacyGooglePaidAttemptStore) RecordLegacyGooglePaidSyncFailure(_ string, transactionID string, _ string, _ int64) error {
	s.failed = append(s.failed, transactionID)
	return nil
}
func (s *fakeLegacyGooglePaidAttemptStore) ClearLegacyGooglePaidSyncFailure(_ string, transactionID string) error {
	s.cleared = append(s.cleared, transactionID)
	return nil
}

func TestLegacyGooglePaidSyncWorkerPersistsPerOrderOutcome(t *testing.T) {
	source := &fakeLegacyGooglePaidSyncSource{
		pending: []string{"ok-1", "bad-1"},
		results: []googleRechargePaidDTO{{TransactionID: "ok-1", SyncedAtMS: 1}, {TransactionID: "bad-1", Error: "temporary"}},
	}
	store := &fakeLegacyGooglePaidAttemptStore{}
	worker := newLegacyGooglePaidSyncWorker([]legacyGooglePaidSyncSource{source}, store, config.FinanceGooglePaidSyncConfig{
		PollInterval:   15 * time.Second,
		BatchSize:      100,
		RequestTimeout: time.Second,
	})

	worker.runOnce(context.Background())

	if len(store.cleared) != 1 || store.cleared[0] != "ok-1" {
		t.Fatalf("cleared = %v, want ok-1", store.cleared)
	}
	if len(store.failed) != 1 || store.failed[0] != "bad-1" {
		t.Fatalf("failed = %v, want bad-1", store.failed)
	}
}
