<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Mail;
use Tests\Feature\Concerns\BuildsFeatureData;
use Tests\TestCase;

class ApplicantAuthFeatureTest extends TestCase
{
    use BuildsFeatureData;
    use DatabaseTransactions;

    public function test_login_page_can_be_opened(): void
    {
        $this->get(route('login'))->assertOk();
    }

    public function test_register_creates_account_and_logs_in(): void
    {
        Mail::fake();
        config(['services.recaptcha.secret_key' => '']);

        // Real flow: user opens login/register page first.
        $this->get(route('login'))->assertOk();

        // Anti-bot guard requires form age >= 3 seconds.
        $startedAt = now()->subSeconds(5)->timestamp;

        $response = $this->withSession([
            'register_started_at' => $startedAt,
        ])->post(route('register'), [
            'name' => 'Pelamar Baru',
            'email' => 'pelamar.baru@example.com',
            'whatsapp' => '081234567899',
            'education' => 'S1',
            'gender' => 'Laki-laki',
            'birth_date' => '2000-01-01',
            'register_started_at' => $startedAt,
        ]);

        $response->assertRedirect(route('dashboard'));
        $response->assertSessionHas('applicant_id');
        $this->assertDatabaseHas('applicants', [
            'email' => 'pelamar.baru@example.com',
        ]);
    }

    public function test_login_with_valid_credentials_redirects_to_dashboard(): void
    {
        $applicant = $this->createApplicant([
            'email' => 'login.berhasil@example.com',
            'password' => 'secret123',
        ]);

        $response = $this->post(route('login.submit'), [
            'email' => $applicant->email,
            'password' => 'secret123',
        ]);

        $response->assertRedirect(route('dashboard'));
        $response->assertSessionHas('applicant_id', $applicant->id);
    }

    public function test_login_with_invalid_credentials_returns_error(): void
    {
        $this->createApplicant([
            'email' => 'login.gagal@example.com',
            'password' => 'secret123',
        ]);

        $response = $this->from(route('login'))->post(route('login.submit'), [
            'email' => 'login.gagal@example.com',
            'password' => 'password-salah',
        ]);

        $response->assertRedirect(route('login'));
        $response->assertSessionHasErrors('email');
    }

    public function test_logout_clears_applicant_session(): void
    {
        $applicant = $this->createApplicant();

        $response = $this->withSession([
            'applicant_id' => $applicant->id,
            'generated_password' => 'abc123',
        ])->post(route('logout'));

        $response->assertRedirect(route('home'));
        $response->assertSessionMissing('applicant_id');
        $response->assertSessionMissing('generated_password');
    }
}
