<?php

namespace Tests\Feature;

use App\Models\Applicant;
use App\Models\Application;
use App\Models\JobListing;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class ApplicationDailyLimitTest extends TestCase
{
    use DatabaseTransactions;

    public function test_applicant_cannot_apply_more_than_three_jobs_within_24_hours(): void
    {
        $applicant = Applicant::create([
            'name' => 'Pelamar Test',
            'email' => 'pelamar@example.com',
            'whatsapp' => '081234567890',
            'education' => 'S1',
            'password' => 'rahasia123',
        ]);

        $jobs = collect(range(1, 4))->map(fn ($i) => $this->createJob($i));

        Application::create([
            'applicant_id' => $applicant->id,
            'job_listing_id' => $jobs[0]->id,
            'status' => 'applied',
            'current_stage' => 0,
            'applied_at' => now()->subHours(2),
        ]);

        Application::create([
            'applicant_id' => $applicant->id,
            'job_listing_id' => $jobs[1]->id,
            'status' => 'applied',
            'current_stage' => 0,
            'applied_at' => now()->subHours(6),
        ]);

        Application::create([
            'applicant_id' => $applicant->id,
            'job_listing_id' => $jobs[2]->id,
            'status' => 'applied',
            'current_stage' => 0,
            'applied_at' => now()->subHours(23),
        ]);

        $limitMessage = 'Kami informasikan bahwa setiap akun hanya dapat melamar maksimal 3 pekerjaan dalam 1 hari. Silakan mencoba kembali untuk melamar pekerjaan lainnya pada hari berikutnya.';

        $response = $this->withSession([
            'applicant_id' => $applicant->id,
        ])->post(route('apply.submit', $jobs[3]));

        $response->assertRedirect(route('home'));
        $response->assertSessionHas('error', $limitMessage);
        $response->assertSessionHas('application_limit_popup', $limitMessage);

        $this->assertSame(3, Application::where('applicant_id', $applicant->id)->count());
        $this->assertDatabaseMissing('applications', [
            'applicant_id' => $applicant->id,
            'job_listing_id' => $jobs[3]->id,
        ]);
    }

    private function createJob(int $index): JobListing
    {
        return JobListing::create([
            'title' => "Posisi {$index}",
            'company' => 'PT Contoh',
            'location' => 'Bandung',
            'type' => 'Full-time',
            'requirements' => 'Minimal pengalaman 1 tahun',
            'description' => 'Deskripsi pekerjaan',
            'is_active' => true,
            'deadline' => now()->addDays(7),
        ]);
    }
}
