package app

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

	"hyapp/pkg/logx"
)

func (a *App) startRedPacketExpiryWorker(ctx context.Context) {
	workerID := "red-packet-expiry-" + a.nodeID
	a.workers.Add(1)
	go func() {
		defer a.workers.Done()
		ticker := time.NewTicker(a.redPacketExpiryWorkerCfg.PollInterval)
		defer ticker.Stop()
		for {
			// 过期退款必须进入 wallet service 用例，保证红包状态、退款流水和 outbox 同一事务提交。
			// 空 app_code 是后台 worker 的“所有租户”语义；repository 会按候选记录的真实 app_code 分事务退款。
			result, err := a.walletSvc.ExpireRedPackets(ctx, "", a.redPacketExpiryWorkerCfg.BatchSize)
			if err != nil && !errors.Is(err, context.Canceled) {
				logx.Error(ctx, "red_packet_expiry_failed", err, slog.String("worker_id", workerID))
			}
			if result.ExpiredCount > 0 {
				logx.Info(ctx, "red_packet_expired",
					slog.String("worker_id", workerID),
					slog.Int64("expired_count", int64(result.ExpiredCount)),
					slog.Int64("refunded_amount", result.RefundedAmount),
				)
			}
			if result.ExpiredCount >= a.redPacketExpiryWorkerCfg.BatchSize {
				continue
			}
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
			}
		}
	}()
}
