package app

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

	"hyapp/pkg/logx"
)

func (a *App) startExternalRechargeReconcileWorker(ctx context.Context) {
	workerID := "external-recharge-reconcile-" + a.nodeID
	a.workers.Add(1)
	go func() {
		defer a.workers.Done()
		ticker := time.NewTicker(a.externalRechargeReconcileWorkerCfg.PollInterval)
		defer ticker.Stop()
		for {
			// 三方回调是主链路；补偿 worker 只兜底 redirected 订单，真正入账仍由 service/storage 的幂等事务收敛。
			// 自动补偿不绑定租户；每笔订单进入 provider 查询和入账前会恢复自己的 app_code context。
			_, err := a.walletSvc.ReconcileExternalRechargeOrders(ctx, "", a.externalRechargeReconcileWorkerCfg.BatchSize)
			if err != nil && !errors.Is(err, context.Canceled) {
				logx.Error(ctx, "external_recharge_reconcile_failed", err, slog.String("worker_id", workerID))
			}
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
			}
		}
	}()
}
