<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Mail\SiteAccessLinkMail;
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\Carbon;
use Illuminate\Support\Facades\Mail;
use Mtc\MercuryDataModels\SiteAccessRequest;

class SendSiteAccessLinkJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(
        public readonly int $requestId,
    ) {
    }

    public function handle(): void
    {
        $request = SiteAccessRequest::query()->find($this->requestId);

        if (!$request || $request->sent_at !== null || $request->expires_at->isPast()) {
            return;
        }

        Mail::to($request->email)->send(new SiteAccessLinkMail($request));

        $request->forceFill(['sent_at' => Carbon::now()])->save();
    }
}
