package app

import (
	"context"
	"errors"
	"log/slog"
	"time"

	"hyapp/pkg/logx"
)

func (a *App) startGooglePaidSyncWorker(ctx context.Context) {
	workerID := "google-paid-sync-" + a.nodeID
	a.workers.Add(1)
	go func() {
		defer a.workers.Done()
		ticker := time.NewTicker(a.googlePaidSyncWorkerCfg.PollInterval)
		defer ticker.Stop()
		for {
			requestCtx, cancel := context.WithTimeout(ctx, a.googlePaidSyncWorkerCfg.RequestTimeout)
			result, err := a.walletSvc.ProcessGooglePaymentPaidSyncBatch(requestCtx, a.googlePaidSyncWorkerCfg.BatchSize)
			cancel()
			if err != nil && !errors.Is(err, context.Canceled) {
				logx.Error(ctx, "google_paid_sync_batch_failed", err, slog.String("worker_id", workerID))
			}
			if result.Claimed > 0 {
				logx.Info(ctx, "google_paid_sync_batch_completed",
					slog.String("worker_id", workerID),
					slog.Int("claimed", result.Claimed),
					slog.Int("succeeded", result.Succeeded),
					slog.Int("failed", result.Failed),
				)
			}
			// A full batch means historical backlog remains. Drain immediately; once caught up, poll every 15 seconds.
			if err == nil && result.Claimed >= a.googlePaidSyncWorkerCfg.BatchSize {
				continue
			}
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
			}
		}
	}()
}
