<?php

declare(strict_types=1);

use App\Filament\System\Pages\Auth\Login;
use App\Models\AuditLog;
use App\Models\PlatformUser;
use App\Models\ManagedEnvironment;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    Filament::setCurrentPanel('system');
    Filament::bootCurrentPanel();
});

it('throttles system login after repeated failures and still audits attempts', function () {
    $platformTenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => null,
        'external_id' => 'platform',
        'name' => 'Platform',
    ]);

    $user = PlatformUser::factory()->create([
        'email' => 'operator@tenantpilot.io',
        'is_active' => true,
    ]);

    for ($i = 0; $i < 10; $i++) {
        Filament::setCurrentPanel('system');
        Filament::bootCurrentPanel();

        Livewire::test(Login::class)
            ->set('data.email', $user->email)
            ->set('data.password', 'wrong-password')
            ->call('authenticate')
            ->assertHasErrors(['data.email']);
    }

    Filament::setCurrentPanel('system');
    Filament::bootCurrentPanel();

    Livewire::test(Login::class)
        ->set('data.email', $user->email)
        ->set('data.password', 'wrong-password')
        ->call('authenticate')
        ->assertHasErrors(['data.email']);

    $auditCount = AuditLog::query()
        ->where('managed_environment_id', $platformTenant->getKey())
        ->where('action', 'platform.auth.login')
        ->count();

    expect($auditCount)->toBe(11);

    $latestAudit = AuditLog::query()
        ->where('managed_environment_id', $platformTenant->getKey())
        ->where('action', 'platform.auth.login')
        ->latest('id')
        ->first();

    expect($latestAudit)->not->toBeNull();
    expect($latestAudit->metadata['reason'] ?? null)->toBe('throttled');
});
