<?php

namespace Tests\Feature;

use App\Models\Admin;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PragmaRX\Google2FA\Google2FA;
use Tests\TestCase;

class AdminAuthenticationTest extends TestCase
{
    use RefreshDatabase;

    public function test_admin_can_sign_in_and_is_redirected_to_dashboard(): void
    {
        $admin = Admin::factory()->create(['password' => 'StrongPassword!123']);

        $response = $this->post(route('admin.login.store'), [
            'email' => $admin->email,
            'password' => 'StrongPassword!123',
            'remember' => true,
        ]);

        $response->assertRedirect(route('admin.dashboard'));
        $this->assertAuthenticatedAs($admin, 'admin');
    }

    public function test_inactive_admin_cannot_sign_in(): void
    {
        $admin = Admin::factory()->create(['password' => 'StrongPassword!123', 'is_active' => false]);

        $this->from(route('admin.login'))->post(route('admin.login.store'), [
            'email' => $admin->email,
            'password' => 'StrongPassword!123',
        ])->assertRedirect(route('admin.login'))->assertSessionHasErrors('email');

        $this->assertGuest('admin');
    }

    public function test_unauthenticated_admin_is_redirected_to_admin_login(): void
    {
        $this->get(route('admin.dashboard'))->assertRedirect(route('admin.login'));
    }

    public function test_expired_admin_session_is_terminated(): void
    {
        $admin = Admin::factory()->create();
        config(['session.admin_timeout' => 1]);

        $this->actingAs($admin, 'admin')
            ->withSession(['admin_last_activity' => now()->subMinutes(2)->timestamp])
            ->get(route('admin.dashboard'))
            ->assertRedirect(route('admin.login'));

        $this->assertGuest('admin');
    }

    public function test_admin_with_two_factor_must_complete_challenge(): void
    {
        $google2fa = new Google2FA;
        $secret = $google2fa->generateSecretKey();
        $admin = Admin::factory()->create([
            'password' => 'StrongPassword!123',
            'two_factor_secret' => $secret,
            'two_factor_confirmed_at' => now(),
        ]);

        $this->post(route('admin.login.store'), [
            'email' => $admin->email,
            'password' => 'StrongPassword!123',
        ])->assertRedirect(route('admin.two-factor.challenge'));
        $this->assertGuest('admin');

        $this->post(route('admin.two-factor.verify'), ['code' => $google2fa->getCurrentOtp($secret)])
            ->assertRedirect(route('admin.dashboard'));
        $this->assertAuthenticatedAs($admin, 'admin');
    }
}
