<?php

namespace Tests\Feature\Jobs;

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

class SavedJobTest extends TestCase
{
    use RefreshDatabase;

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

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

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

    public function test_fully_unlocked_users_can_save_and_unsave_jobs(): void
    {
        $user = $this->unlockedUser();
        $job = $this->remoteJob();

        $this
            ->actingAs($user)
            ->from(route('jobs.index'))
            ->post(route('jobs.save', $job))
            ->assertRedirect(route('jobs.index'));

        $this->assertDatabaseHas('saved_jobs', [
            'user_id' => $user->id,
            'imported_job_id' => $job->id,
        ]);
        $this->assertDatabaseHas('job_interests', [
            'user_id' => $user->id,
            'imported_job_id' => $job->id,
            'source' => 'saved',
        ]);

        $this
            ->actingAs($user)
            ->from(route('jobs.index'))
            ->delete(route('jobs.unsave', $job))
            ->assertRedirect(route('jobs.index'));

        $this->assertDatabaseMissing('saved_jobs', [
            'user_id' => $user->id,
            'imported_job_id' => $job->id,
        ]);
    }

    public function test_save_and_unsave_can_return_json_for_ajax_requests(): void
    {
        $user = $this->unlockedUser();
        $job = $this->remoteJob();

        $this
            ->actingAs($user)
            ->withHeader('Accept', 'application/json')
            ->post(route('jobs.save', $job))
            ->assertOk()
            ->assertJson([
                'message' => 'Job saved.',
                'saved' => true,
                'saved_count' => 1,
            ]);

        $this->assertDatabaseHas('saved_jobs', [
            'user_id' => $user->id,
            'imported_job_id' => $job->id,
        ]);

        $this
            ->actingAs($user)
            ->withHeader('Accept', 'application/json')
            ->delete(route('jobs.unsave', $job))
            ->assertOk()
            ->assertJson([
                'message' => 'Saved job removed.',
                'saved' => false,
                'saved_count' => 0,
            ]);

        $this->assertDatabaseMissing('saved_jobs', [
            'user_id' => $user->id,
            'imported_job_id' => $job->id,
        ]);
    }

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

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

        return ImportedJob::query()->create([
            'job_source_id' => $source->id,
            'external_id' => 'save-test-001',
            'title' => 'Remote Operations Coordinator',
            'company' => 'Remote Ops Co',
            'category' => 'operations',
            'employment_type' => 'full_time',
            'experience_level' => 'mid',
            'location_type' => 'remote',
            'summary' => 'Coordinate remote operations across async teams.',
            'description' => 'Manage documentation, handoffs, reporting, and process hygiene.',
            'skills' => ['Operations', 'Documentation'],
            'tags' => ['remote', 'operations'],
            'source_url' => 'https://save-source.example/jobs/ops',
            'apply_url' => 'https://save-source.example/jobs/ops/apply',
            'source_attribution' => 'Source: Save Test Source',
            'status' => ImportedJob::STATUS_ACTIVE,
            'posted_at' => now(),
            'last_seen_at' => now(),
        ]);
    }
}
