<?php

namespace Tests\Feature\Jobs;

use App\Jobs\SendApprovalRequestEmail;
use App\Mail\ApprovalRequestMail;
use App\Models\ApprovalStep;
use App\Models\ApprovalWorkflow;
use App\Models\TravelRequest;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;

class SendApprovalRequestEmailTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(RoleSeeder::class);
    }

    public function test_email_is_sent_to_users_with_role(): void
    {
        Mail::fake();

        $approver = User::factory()->create();
        $approver->assignRole('travel_approver');

        $workflow = ApprovalWorkflow::factory()->create(['is_active' => true]);
        ApprovalStep::factory()->create(['workflow_id' => $workflow->id, 'order' => 1, 'role' => 'travel_approver']);

        $staff = User::factory()->create();
        $request = TravelRequest::factory()->create([
            'user_id' => $staff->id,
            'workflow_id' => $workflow->id,
        ]);

        SendApprovalRequestEmail::dispatch($request, 'travel_approver');
        (new SendApprovalRequestEmail($request, 'travel_approver'))->handle();

        Mail::assertQueued(ApprovalRequestMail::class, fn ($mail) => $mail->hasTo($approver->email));
    }

    public function test_no_email_sent_when_no_users_with_role(): void
    {
        Mail::fake();

        $staff = User::factory()->create();
        $request = TravelRequest::factory()->create(['user_id' => $staff->id]);

        (new SendApprovalRequestEmail($request, 'travel_approver'))->handle();

        Mail::assertNothingSent();
    }
}
