<?php
namespace App\Jobs\Admin\Mail;

use App\Repositories\Admin\Mail\AdminMailRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

final class DispatchMailBatchJob implements ShouldQueue
{
    use Dispatchable, Queueable;

    public $tries = 1;

    public function __construct(public int $batchId) {}

    public function handle(AdminMailRepository $repo): void
    {
        $b = $repo->findBatch($this->batchId);
        if (!$b) return;

        if (in_array((string)$b->status, ['canceled','sent','failed','partial'], true)) return;

        // sending 상태로 전환
        $repo->markBatchSending($this->batchId);

        // queued 아이템을 일정량씩 job으로 뿌림
        $items = $repo->nextQueuedItems($this->batchId, 500);
        foreach ($items as $it) {
            SendMailItemJob::dispatch($this->batchId, (int)$it->id)->onQueue('mail');
        }
    }
}
