<?php

/**
 * 文件功能：扫描协议离婚超时自动升级处理（72h无响应则自动解除）
 *
 * 每小时执行一次，超时的协议离婚申请自动执行发起方惩罚并解除婚姻。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Jobs;

use App\Events\MarriageDivorced;
use App\Models\Marriage;
use App\Services\MarriageConfigService;
use App\Services\MarriageService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class AutoExpireDivorces implements ShouldQueue
{
    use Queueable;

    /**
     * 执行 Job：扫描离婚申请超时并自动解除。
     */
    public function handle(MarriageService $service, MarriageConfigService $config): void
    {
        // 超时小时数从配置读取（默认72h）
        $timeoutHours = $config->get('divorce_request_timeout', 72);

        Marriage::query()
            ->where('status', 'married')
            ->where('divorce_type', 'mutual')
            ->whereNotNull('divorce_requested_at')
            ->where('divorce_requested_at', '<=', now()->subHours($timeoutHours))
            ->cursor()
            ->each(function (Marriage $marriage) use ($service) {
                $service->autoExpireDivorce($marriage);
                $marriage->refresh();
                broadcast(new MarriageDivorced($marriage, 'auto'));
            });
    }
}
