<?php

namespace App\Jobs;

use App\Mail\Reminders\DynamicReminderMail;
use App\Models\ReminderLog;
use App\Services\NotificationLogService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class SendReminderEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;

    /**
     * @param  list<array{content: string, as: string, mime: string}>  $binaryAttachments
     * @param  list<string>  $ccAddresses
     */
    public function __construct(
        public int $reminderLogId,
        public string $subjectLine,
        public string $htmlBody,
        public string $textBody,
        public array $binaryAttachments = [],
        public array $ccAddresses = []
    ) {}

    public function handle(NotificationLogService $logService): void
    {
        $log = ReminderLog::query()->find($this->reminderLogId);
        if (! $log) {
            return;
        }

        try {
            Mail::to($log->recipient_email)->send(new DynamicReminderMail(
                $this->subjectLine,
                $this->htmlBody,
                $this->textBody,
                $this->binaryAttachments,
                $this->ccAddresses
            ));

            $logService->markSent($log);
        } catch (\Throwable $e) {
            Log::warning('SendReminderEmailJob failed: '.$e->getMessage(), [
                'reminder_log_id' => $this->reminderLogId,
            ]);
            $logService->markFailed($log, $e->getMessage());
            throw $e;
        }
    }
}
