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

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

final class SendMailItemJob implements ShouldQueue
{
    use Dispatchable, Queueable;

    public $tries = 3;
    public $backoff = [10, 60, 180]; // 재시도 간격

    public function __construct(public int $batchId, public int $itemId) {}

    public function middleware(): array
    {
        return [new RateLimited('admin-mail-smtp')];
    }

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

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

        $item = \DB::table('admin_mail_batch_items')->where('id',$this->itemId)->first();
        if (!$item) return;
        if ((string)$item->status !== 'queued') return;

        $svc->sendItem($batch, $item);
        $svc->refreshBatchProgress($this->batchId);

        // 아직 queued가 남아있으면 계속 뿌리기(가벼운 자기재호출)
        if (\DB::table('admin_mail_batch_items')->where('batch_id',$this->batchId)->where('status','queued')->exists()) {
            DispatchMailBatchJob::dispatch($this->batchId)->onQueue('mail');
        }
    }
}
