<?php

namespace App\Jobs;

use App\Models\EmailMessage;
use App\Services\Email\EmailSenderService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class SendEmailMessageJob implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    /** @var list<int> */
    public array $backoff = [30, 120, 300];

    public function __construct(
        public int $emailMessageId,
    ) {}

    public function handle(EmailSenderService $sender): void
    {
        $message = EmailMessage::query()->with('attachments')->find($this->emailMessageId);

        if ($message === null) {
            return;
        }

        if ($message->scheduled_at && $message->scheduled_at->isFuture()) {
            $this->release($message->scheduled_at->diffInSeconds(now()));

            return;
        }

        try {
            $sender->sendNow($message);
        } catch (\Throwable $e) {
            Log::error('SendEmailMessageJob failed', [
                'email_message_id' => $this->emailMessageId,
                'attempt' => $this->attempts(),
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
