<?php

namespace Tests\Feature\Auth;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class PasswordLoginTest extends TestCase
{
    use RefreshDatabase;

    public function test_login_page_shows_google_and_password_login_options(): void
    {
        $response = $this->get(route('login'));

        $response
            ->assertOk()
            ->assertSee('Continue with Google')
            ->assertSee('Username or email')
            ->assertSee('Forgot password?');
    }

    public function test_user_can_login_with_email_and_password(): void
    {
        $user = User::factory()->create([
            'email' => 'candidate@example.com',
            'username' => 'candidate',
            'password' => Hash::make('Secret123'),
            'password_set_at' => now(),
        ]);

        $response = $this->post(route('login.store'), [
            'identifier' => 'candidate@example.com',
            'password' => 'Secret123',
        ]);

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

    public function test_user_can_login_with_username_and_password(): void
    {
        $user = User::factory()->create([
            'username' => 'remote_candidate',
            'password' => Hash::make('Secret123'),
            'password_set_at' => now(),
            'questionnaire_completed_at' => now(),
            'access_unlocked_at' => now(),
            'resume_analyzed_at' => now(),
            'profile_completed_at' => now(),
        ]);

        $response = $this->post(route('login.store'), [
            'identifier' => 'remote_candidate',
            'password' => 'Secret123',
        ]);

        $response->assertRedirect(route('applicant.dashboard'));
        $this->assertAuthenticatedAs($user);
    }

    public function test_google_only_users_without_set_password_cannot_login_with_password(): void
    {
        User::factory()->create([
            'email' => 'candidate@example.com',
            'password' => Hash::make('Secret123'),
            'password_set_at' => null,
        ]);

        $response = $this->from(route('login'))->post(route('login.store'), [
            'identifier' => 'candidate@example.com',
            'password' => 'Secret123',
        ]);

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

        $this->assertGuest();
    }
}
