<?php

namespace Tests\Feature;

use App\Models\Admin;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\RateLimiter;
use Tests\TestCase;

class AuthenticationSecurityTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        RateLimiter::clear('attacker@example.test|127.0.0.1');
        parent::tearDown();
    }

    public function test_login_rejects_invalid_email_and_oversized_password(): void
    {
        $this->from(route('admin.login'))->post(route('admin.login.store'), [
            'email' => 'not-an-email',
            'password' => str_repeat('A', 256),
        ])->assertSessionHasErrors(['email', 'password']);
    }

    public function test_login_is_rate_limited_after_repeated_failures(): void
    {
        config(['security.admin_login.max_attempts' => 2]);

        $payload = ['email' => 'attacker@example.test', 'password' => 'WrongPassword!123'];
        $this->post(route('admin.login.store'), $payload);
        $this->post(route('admin.login.store'), $payload);

        $this->post(route('admin.login.store'), $payload)
            ->assertSessionHasErrors(['email' => 'Too many sign-in attempts. Try again in 60 seconds.']);
    }

    public function test_logout_invalidates_authenticated_session(): void
    {
        $admin = Admin::factory()->create();

        $this->actingAs($admin, 'admin')->post(route('admin.logout'))->assertRedirect(route('admin.login'));
        $this->assertGuest('admin');
    }
}
