<?php

namespace Tests\Feature\Jobs;

use App\Models\ImportedJob;
use App\Models\JobSource;
use App\Models\Profile;
use App\Models\QuestionnaireResponse;
use App\Models\ResumeReport;
use App\Models\User;
use App\Services\Settings\SettingsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class JobDashboardRenderingTest extends TestCase
{
    use RefreshDatabase;

    public function test_jobs_dashboard_does_not_render_external_apply_url(): void
    {
        app(SettingsService::class)->set('matching', 'show_jobs_without_salary', true, 'boolean');

        $user = $this->unlockedUser();
        $job = $this->remoteJob();

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

        $response
            ->assertOk()
            ->assertSee('Remote Customer Success Manager')
            ->assertSee('Apply')
            ->assertSee('Matched jobs')
            ->assertSee(route('jobs.index', ['saved' => 1]), false)
            ->assertSee(route('jobs.index', ['applied' => 1]), false)
            ->assertSee(route('jobs.apply', $job), false)
            ->assertSee('target="_blank"', false)
            ->assertDontSee($job->apply_url, false)
            ->assertDontSee($job->source_url, false);
    }

    public function test_job_detail_is_protected_and_does_not_render_external_urls(): void
    {
        $user = $this->unlockedUser();
        $job = $this->remoteJob([
            'summary' => '<p><strong>Lead customer success</strong> for async teams.</p>',
            'description' => '<p><strong>Own onboarding</strong>, CRM hygiene, and documentation.</p><p>Apply at https://remote-board.example/jobs/remote-csm-001/apply?token=secret-apply-url</p>',
        ]);

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

        $response
            ->assertOk()
            ->assertSee('Remote Customer Success Manager')
            ->assertSee('Lead customer success')
            ->assertSee('Own onboarding')
            ->assertSee('Job snapshot')
            ->assertSee('Full role details')
            ->assertSee('Your job lists')
            ->assertSee('Apply and track')
            ->assertSee(route('jobs.apply', $job), false)
            ->assertSee('target="_blank"', false)
            ->assertDontSee('&lt;strong&gt;', false)
            ->assertDontSee('<strong>', false)
            ->assertDontSee($job->apply_url, false)
            ->assertDontSee($job->source_url, false);
    }

    public function test_jobs_dashboard_filters_by_category_and_minimum_salary(): void
    {
        app(SettingsService::class)->set('matching', 'show_low_match_jobs', true, 'boolean');

        $user = $this->unlockedUser();
        $matchingJob = $this->remoteJob([
            'external_id' => 'filtered-match',
            'title' => 'Remote Customer Success Manager',
            'category' => 'support',
            'salary_currency' => 'USD',
            'salary_min' => 5000,
            'salary_max' => 7000,
        ]);
        $filteredOutJob = $this->remoteJob([
            'external_id' => 'filtered-out',
            'title' => 'Remote Finance Analyst',
            'category' => 'finance',
            'salary_currency' => 'USD',
            'salary_min' => 3000,
            'salary_max' => 4000,
        ]);

        $response = $this
            ->actingAs($user)
            ->get(route('jobs.index', [
                'category' => 'support',
                'salary_min' => 5000,
            ]));

        $response
            ->assertOk()
            ->assertSee($matchingJob->title)
            ->assertSee('$5,000 - $7,000')
            ->assertSee('salary-badge', false)
            ->assertDontSee($filteredOutJob->title);
    }

    public function test_jobs_dashboard_paginates_ranked_jobs(): void
    {
        app(SettingsService::class)->set('matching', 'show_low_match_jobs', true, 'boolean');

        $user = $this->unlockedUser();

        foreach (range(1, 12) as $index) {
            $this->remoteJob([
                'external_id' => 'paginated-job-'.$index,
                'title' => sprintf('Paginated Remote Role %02d', $index),
                'salary_currency' => 'USD',
                'salary_min' => 5000,
                'salary_max' => 7000,
                'posted_at' => now()->subMinutes($index),
            ]);
        }

        $this
            ->actingAs($user)
            ->get(route('jobs.index'))
            ->assertOk()
            ->assertSee('Showing 1-10 of 12')
            ->assertSee('Page 1 of 2')
            ->assertSee('Paginated Remote Role 01')
            ->assertDontSee('Paginated Remote Role 11');

        $this
            ->actingAs($user)
            ->get(route('jobs.index', ['page' => 2]))
            ->assertOk()
            ->assertSee('Showing 11-12 of 12')
            ->assertSee('Page 2 of 2')
            ->assertSee('Paginated Remote Role 11')
            ->assertDontSee('Paginated Remote Role 01');
    }

    private function unlockedUser(): User
    {
        $user = User::factory()->create([
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => now(),
            'resume_uploaded_at' => now(),
            'resume_analyzed_at' => now(),
            'profile_completed_at' => now(),
        ]);

        QuestionnaireResponse::query()->create([
            'user_id' => $user->id,
            'answers' => ['goal' => 'Find remote customer success jobs'],
            'preferred_categories' => ['support'],
            'preferred_roles' => ['Customer Success Manager'],
            'skills' => ['Customer success', 'CRM', 'Documentation'],
            'experience_level' => 'mid',
            'availability' => 'immediate',
            'country_code' => 'IN',
            'salary_currency' => 'INR',
            'salary_min' => 1200000,
            'open_to_contract' => false,
            'open_to_full_time' => true,
            'completed_at' => now(),
        ]);

        ResumeReport::query()->create([
            'user_id' => $user->id,
            'original_filename' => 'resume.txt',
            'disk' => 'local',
            'path' => 'resumes/'.$user->id.'/resume.txt',
            'mime_type' => 'text/plain',
            'size_bytes' => 4096,
            'status' => ResumeReport::STATUS_COMPLETED,
            'ats_score' => 88,
            'remote_readiness_score' => 84,
            'extracted_skills' => ['Customer success', 'CRM', 'Documentation'],
            'role_suggestions' => ['Customer Success Manager'],
            'missing_keywords' => [],
            'resume_improvements' => [],
            'analysis' => ['summary' => 'Strong customer success profile.'],
            'analyzed_at' => now(),
        ]);

        Profile::query()->create([
            'user_id' => $user->id,
            'headline' => 'Remote customer success manager',
            'summary' => 'Customer success leader for remote teams.',
            'current_role' => 'Customer Success Manager',
            'experience_level' => 'mid',
            'country_code' => 'IN',
            'timezone' => 'Asia/Kolkata',
            'skills' => ['Customer success', 'CRM', 'Documentation'],
            'preferred_roles' => ['Customer Success Manager'],
            'preferred_categories' => ['support'],
            'availability' => 'immediate',
            'salary_currency' => 'INR',
            'salary_min' => 1200000,
            'open_to_contract' => false,
            'open_to_full_time' => true,
            'completed_at' => now(),
        ]);

        return $user;
    }

    /**
     * @param  array<string, mixed>  $overrides
     */
    private function remoteJob(array $overrides = []): ImportedJob
    {
        $source = JobSource::query()->firstOrCreate([
            'slug' => 'remote-board',
        ], [
            'name' => 'Remote Board',
            'type' => 'manual',
            'base_url' => 'https://remote-board.example',
            'attribution_text' => 'Source: Remote Board',
            'is_active' => true,
        ]);

        return ImportedJob::query()->create(array_replace([
            'job_source_id' => $source->id,
            'external_id' => 'remote-csm-001',
            'title' => 'Remote Customer Success Manager',
            'company' => 'Distributed Care Co',
            'category' => 'support',
            'employment_type' => 'full_time',
            'experience_level' => 'mid',
            'location_type' => 'remote',
            'country_code' => 'IN',
            'summary' => 'Lead customer success for async remote customers.',
            'description' => 'Own onboarding, CRM hygiene, customer health, and documentation.',
            'skills' => ['Customer success', 'CRM', 'Documentation'],
            'tags' => ['remote', 'support'],
            'source_url' => 'https://remote-board.example/jobs/remote-csm-001',
            'apply_url' => 'https://remote-board.example/jobs/remote-csm-001/apply?token=secret-apply-url',
            'source_attribution' => 'Source: Remote Board',
            'status' => ImportedJob::STATUS_ACTIVE,
            'posted_at' => now(),
            'last_seen_at' => now(),
        ], $overrides));
    }
}
