<?php

/**
 * 文件功能：触发定时婚礼（到时间后自动执行红包分发）
 *
 * 每 5 分钟执行一次，扫描 ceremony_at <= now() 且 status=pending 的婚礼，
 * 调用 WeddingService::trigger() 分发红包并广播庆典事件。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Jobs;

use App\Events\WeddingCelebration;
use App\Models\WeddingCeremony;
use App\Services\WeddingService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class TriggerScheduledWeddings implements ShouldQueue
{
    use Queueable;

    /**
     * 执行 Job：检查并触发到时的定时婚礼。
     */
    public function handle(WeddingService $wedding): void
    {
        WeddingCeremony::query()
            ->where('status', 'pending')
            ->where('ceremony_type', 'scheduled')
            ->where('ceremony_at', '<=', now())
            ->with('marriage')
            ->cursor()
            ->each(function (WeddingCeremony $ceremony) use ($wedding) {
                if (! $ceremony->marriage) {
                    return;
                }

                $result = $wedding->trigger($ceremony);

                if ($result['ok']) {
                    // 广播全房间婚礼庆典
                    broadcast(new WeddingCelebration($ceremony, $ceremony->marriage));
                }
            });
    }
}
