<?php

namespace App\Jobs;

use App\Mail\ApprovalRequestMail;
use App\Models\TravelRequest;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;

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

    public function __construct(
        public readonly TravelRequest $travelRequest,
        public readonly string $role,
    ) {}

    public function handle(): void
    {
        $approvers = User::role($this->role)->get();

        foreach ($approvers as $approver) {
            $signedUrl = URL::signedRoute('travel-requests.approve', ['id' => $this->travelRequest->id]);
            Mail::to($approver->email)->queue(new ApprovalRequestMail($this->travelRequest, $approver, $signedUrl));
        }
    }
}
