package app

import "context"

func (a *App) runBackgroundWorkers() {
	if a.walletSvc == nil {
		return
	}
	ctx, cancel := context.WithCancel(context.Background())
	a.stopWorker = cancel
	if a.outboxWorkerCfg.Enabled && a.outboxProducer != nil {
		excludedRealtimeTypes := []string(nil)
		if a.realtimeOutboxWorkerCfg.Enabled && a.realtimeOutboxProducer != nil {
			// 普通账务 worker 在实时通道可用时跳过红包 UI 事件，避免两个 worker 抢同一行。
			excludedRealtimeTypes = a.realtimeOutboxWorkerCfg.EventTypes
		}
		a.startWalletOutboxWorkers(ctx, "wallet-outbox", a.outboxWorkerCfg, a.outboxPartitions, a.outboxProducer, a.walletOutboxTopic, nil, excludedRealtimeTypes)
	}
	if a.realtimeOutboxWorkerCfg.Enabled && a.realtimeOutboxProducer != nil {
		a.startWalletOutboxWorkers(ctx, "wallet-realtime-outbox", a.realtimeOutboxWorkerCfg, a.realtimeOutboxPartitions, a.realtimeOutboxProducer, a.realtimeWalletOutboxTopic, a.realtimeOutboxWorkerCfg.EventTypes, nil)
	}
	if a.outboxArchiveCfg.Enabled {
		// 归档与 MQ fanout 独立；purge 另有恢复凭证、exact membership 和 allowlist 三重门槛。
		a.startWalletOutboxArchiveWorker(ctx)
	}
	if a.outboxArchiveCfg.PurgeEnabled {
		a.startWalletOutboxPurgeWorker(ctx)
	}
	if a.externalRechargeReconcileWorkerCfg.Enabled {
		a.startExternalRechargeReconcileWorker(ctx)
	}
	if a.googlePaidSyncWorkerCfg.Enabled {
		a.startGooglePaidSyncWorker(ctx)
	}
	if a.redPacketExpiryWorkerCfg.Enabled {
		a.startRedPacketExpiryWorker(ctx)
	}
	if a.resourceEquipmentCleanupWorkerCfg.Enabled {
		// 装备残留是 Wallet owner 数据；多副本只由 advisory lock winner 执行物理删除，
		// gateway/cron 都不能直连钱包库或在用户请求内代做清理。
		a.startResourceEquipmentCleanupWorker(ctx)
	}
}
