<?php

namespace Tests\Feature;

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

class PopunderStageFormTest extends TestCase
{
    use DatabaseTransactions;

    public function test_stage_4_form_has_smartlink_trigger_and_submission_script_when_smartlink_is_active(): void
    {
        $this->disableExistingPopunderAds();

        $applicant = $this->createApplicant();
        $job = $this->createJob();
        $stages = $this->createStages($job, 5);
        $stage4 = $stages[4];

        $application = $this->createApplicationRecord($applicant, $job, 'stage4_passed');
        $this->createActivePopunderAd();

        $response = $this->withSession([
            'applicant_id' => $applicant->id,
        ])->get(route('form.stage', [$application, $stage4]));

        $response->assertOk();
        $response->assertSee('data-smartlink', false);
        $response->assertSee('data-smartlink-form', false);
        $response->assertSee("document.querySelectorAll('form[data-smartlink-form]')", false);
        $response->assertSee('var smartlinkUrl =', false);
        $response->assertSee("window.open(smartlinkUrl, '_blank')", false);
    }

    public function test_stage_5_form_has_smartlink_trigger_when_smartlink_is_active(): void
    {
        $this->disableExistingPopunderAds();

        $applicant = $this->createApplicant('pelamar5@example.com');
        $job = $this->createJob('Posisi Tahap 5');
        $stages = $this->createStages($job, 5);
        $stage5 = $stages[5];

        $application = $this->createApplicationRecord($applicant, $job, 'stage5_passed');
        $this->createActivePopunderAd();

        $response = $this->withSession([
            'applicant_id' => $applicant->id,
        ])->get(route('form.stage', [$application, $stage5]));

        $response->assertOk();
        $response->assertSee('data-smartlink', false);
    }

    public function test_stage_3_form_has_smartlink_trigger_when_smartlink_is_active(): void
    {
        $this->disableExistingPopunderAds();

        $applicant = $this->createApplicant('pelamar3@example.com');
        $job = $this->createJob('Posisi Tahap 3');
        $stages = $this->createStages($job, 5);
        $stage3 = $stages[3];

        $application = $this->createApplicationRecord($applicant, $job, 'stage3_passed');
        $this->createActivePopunderAd();

        $response = $this->withSession([
            'applicant_id' => $applicant->id,
        ])->get(route('form.stage', [$application, $stage3]));

        $response->assertOk();
        $response->assertSee('data-smartlink', false);
        $response->assertSee('data-smartlink-form', false);
        $response->assertSee("document.querySelectorAll('form[data-smartlink-form]')", false);
        $response->assertSee('var smartlinkUrl =', false);
        $response->assertSee("window.open(smartlinkUrl, '_blank')", false);
    }

    public function test_stage_4_form_without_active_smartlink_ad_has_no_smartlink_script(): void
    {
        $this->disableExistingPopunderAds();

        $applicant = $this->createApplicant('pelamar-noad@example.com');
        $job = $this->createJob('Posisi No Ad');
        $stages = $this->createStages($job, 5);
        $stage4 = $stages[4];

        $application = $this->createApplicationRecord($applicant, $job, 'stage4_passed');

        $response = $this->withSession([
            'applicant_id' => $applicant->id,
        ])->get(route('form.stage', [$application, $stage4]));

        $response->assertOk();
        $response->assertSee('data-smartlink', false);
        $response->assertDontSee("document.querySelectorAll('form[data-smartlink-form]')", false);
    }

    private function createApplicant(string $email = 'pelamar@example.com'): Applicant
    {
        return Applicant::create([
            'name' => 'Pelamar Uji',
            'email' => $email,
            'whatsapp' => '081234567890',
            'education' => 'S1',
            'password' => 'rahasia123',
        ]);
    }

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

    /**
     * @return array<int, JobStage>
     */
    private function createStages(JobListing $job, int $maxStage): array
    {
        $stages = [];
        for ($i = 1; $i <= $maxStage; $i++) {
            $stages[$i] = JobStage::create([
                'job_listing_id' => $job->id,
                'stage_number' => $i,
                'name' => "Tahap {$i}",
                'description' => "Deskripsi tahap {$i}",
                'form_fields' => [
                    [
                        'name' => 'catatan',
                        'label' => 'Catatan',
                        'type' => 'text',
                        'required' => true,
                    ],
                ],
                'is_active' => true,
                'sort_order' => $i,
            ]);
        }

        return $stages;
    }

    private function createApplicationRecord(Applicant $applicant, JobListing $job, string $status): Application
    {
        return Application::create([
            'applicant_id' => $applicant->id,
            'job_listing_id' => $job->id,
            'status' => $status,
            'current_stage' => 0,
            'applied_at' => now()->subDay(),
        ]);
    }

    private function createActivePopunderAd(): Ad
    {
        return Ad::create([
            'name' => 'Smartlink Test',
            'description' => 'Untuk test smartlink',
            'position' => 'popunder',
            'size' => null,
            'code' => 'https://ballisticcomainvitation.com/f29mp7rw?key=b4f005baea672071e1f04c6568446157',
            'is_active' => true,
            'sort_order' => 0,
        ]);
    }

    private function disableExistingPopunderAds(): void
    {
        Ad::where('position', 'popunder')->update(['is_active' => false]);
    }
}
