<?php

namespace Tests\Feature\Jobs;

use App\Models\Application;
use App\Models\ImportedJob;
use App\Models\JobSource;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class JobAccessProtectionTest extends TestCase
{
    use RefreshDatabase;

    public function test_jobs_dashboard_redirects_users_without_completed_questionnaire(): void
    {
        $user = User::factory()->create(['questionnaire_completed_at' => null]);

        $response = $this->actingAs($user)->get(route('jobs.index'));

        $response->assertRedirect(route('questionnaire.show'));
    }

    public function test_jobs_dashboard_redirects_unpaid_users_to_checkout(): void
    {
        $user = User::factory()->create([
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => null,
        ]);

        $response = $this->actingAs($user)->get(route('jobs.index'));

        $response->assertRedirect(route('payment.checkout'));
    }

    public function test_jobs_dashboard_redirects_users_without_resume_analysis(): void
    {
        $user = User::factory()->create([
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => now(),
            'resume_analyzed_at' => null,
        ]);

        $response = $this->actingAs($user)->get(route('jobs.index'));

        $response->assertRedirect(route('resume.show'));
    }

    public function test_apply_redirects_locked_users_before_tracking_application(): void
    {
        $user = User::factory()->create([
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => null,
        ]);
        $job = $this->remoteJob();

        $response = $this->actingAs($user)->post(route('jobs.apply', $job));

        $response->assertRedirect(route('payment.checkout'));
        $this->assertDatabaseCount('applications', 0);
    }

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

        $response = $this->actingAs($user)->post(route('jobs.apply', $job));

        $response->assertRedirect($job->apply_url);
        $this->assertDatabaseHas('applications', [
            'user_id' => $user->id,
            'imported_job_id' => $job->id,
            'job_source_id' => $job->job_source_id,
            'source_url' => $job->source_url,
            'apply_url' => $job->apply_url,
            'status' => Application::STATUS_APPLIED,
        ]);
    }

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

        $this->actingAs($user)->post(route('jobs.apply', $job));

        $application = $user->applications()->firstOrFail();
        $followUpDate = now()->addWeek()->format('Y-m-d');

        $response = $this
            ->actingAs($user)
            ->from(route('jobs.index'))
            ->patch(route('applications.update', $application), [
                'status' => Application::STATUS_INTERVIEW,
                'notes' => 'Recruiter replied with a screening call.',
                'follow_up_at' => $followUpDate,
            ]);

        $response->assertRedirect(route('jobs.index'));
        $this->assertDatabaseHas('applications', [
            'id' => $application->id,
            'status' => Application::STATUS_INTERVIEW,
            'notes' => 'Recruiter replied with a screening call.',
            'follow_up_at' => $followUpDate.' 00:00:00',
        ]);
    }

    private function remoteJob(): ImportedJob
    {
        $source = JobSource::query()->create([
            'name' => 'Manual Test Source',
            'slug' => 'manual-test-source',
            'type' => 'manual',
            'base_url' => 'https://jobs.example.test',
            'attribution_text' => 'Source: Manual Test Source',
            'is_active' => true,
        ]);

        return ImportedJob::query()->create([
            'job_source_id' => $source->id,
            'external_id' => 'remote-support-001',
            'title' => 'Remote Customer Support Specialist',
            'company' => 'Acme Remote',
            'category' => 'support',
            'employment_type' => 'full_time',
            'experience_level' => 'mid',
            'location_type' => 'remote',
            'summary' => 'Support customers asynchronously across global time zones.',
            'description' => 'A remote-first support role for customer success and helpdesk workflows.',
            'skills' => ['Customer support', 'CRM', 'Documentation'],
            'tags' => ['remote', 'support'],
            'source_url' => 'https://jobs.example.test/remote-support',
            'apply_url' => 'https://jobs.example.test/remote-support/apply',
            'source_attribution' => 'Source: Manual Test Source',
            'status' => ImportedJob::STATUS_ACTIVE,
            'posted_at' => now(),
            'last_seen_at' => now(),
        ]);
    }
}
