<?php

namespace Tests\Feature\Policies;

use App\Models\ImportedJob;
use App\Models\JobSource;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Gate;
use Tests\TestCase;

class ImportedJobPolicyTest extends TestCase
{
    use RefreshDatabase;

    public function test_users_cannot_apply_to_inactive_jobs(): void
    {
        $user = User::factory()->create([
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => now(),
            'resume_analyzed_at' => now(),
            'profile_completed_at' => now(),
        ]);
        $job = $this->remoteJob(['status' => ImportedJob::STATUS_INACTIVE]);

        $this->assertFalse(Gate::forUser($user)->allows('apply', $job));
    }

    public function test_users_cannot_apply_to_expired_jobs(): void
    {
        $user = User::factory()->create([
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => now(),
            'resume_analyzed_at' => now(),
            'profile_completed_at' => now(),
        ]);
        $job = $this->remoteJob([
            'status' => ImportedJob::STATUS_ACTIVE,
            'expires_at' => now()->subDay(),
        ]);

        $this->assertFalse(Gate::forUser($user)->allows('apply', $job));
    }

    /**
     * @param  array<string, mixed>  $overrides
     */
    private function remoteJob(array $overrides = []): ImportedJob
    {
        $source = JobSource::query()->create([
            'name' => 'Policy Source',
            'slug' => 'policy-source',
            'type' => 'manual',
            'is_active' => true,
        ]);

        return ImportedJob::query()->create(array_replace([
            'job_source_id' => $source->id,
            'external_id' => 'policy-job',
            'title' => 'Remote Policy Role',
            'company' => 'Policy Co',
            'category' => 'general',
            'source_url' => 'https://policy.example/jobs/1',
            'apply_url' => 'https://policy.example/jobs/1/apply',
            'status' => ImportedJob::STATUS_ACTIVE,
        ], $overrides));
    }
}
