<?php

namespace Tests\Feature\Auth;

use App\Domains\Auth\Models\LoginAttempt;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Permission;
use App\Domains\Authorization\Models\Role;
use App\Domains\Notification\Events\PasswordResetRequested;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class ScannerLoginControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_logs_in_a_tenant_bound_user_with_scan_permission(): void
    {
        $role = Role::query()->create([
            'codigo' => RoleCode::AdminApp->value,
            'nombre' => 'Operador',
        ]);
        $permission = Permission::query()->create([
            'codigo' => PermissionCode::ScanTickets->value,
            'nombre' => 'Escanear tickets',
        ]);
        $role->permissions()->attach($permission->codigo);
        $tenant = Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.test',
        ]);
        $user = User::factory()->create([
            'email' => 'scanner@example.com',
            'password' => Hash::make('secret123'),
            'rol_codigo' => $role->codigo,
            'tenant_codigo' => $tenant->codigo,
        ]);

        $response = $this->postJson('/api/v1/scanner/login', [
            'email' => ' SCANNER@EXAMPLE.COM ',
            'password' => 'secret123',
        ]);

        $response
            ->assertOk()
            ->assertJsonPath('user.id', $user->id)
            ->assertJsonPath('user.rol_codigo', RoleCode::AdminApp->value)
            ->assertJsonPath('token_type', 'Bearer');

        $this->assertSame(['scanner'], $user->tokens()->sole()->abilities);
    }

    public function test_it_rejects_a_user_without_scan_permission(): void
    {
        $role = Role::query()->create([
            'codigo' => RoleCode::Scanner->value,
            'nombre' => 'Scanner sin permiso',
        ]);
        $tenant = Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.test',
        ]);
        $user = User::factory()->create([
            'email' => 'customer@example.com',
            'password' => Hash::make('secret123'),
            'rol_codigo' => $role->codigo,
            'tenant_codigo' => $tenant->codigo,
        ]);

        $this->postJson('/api/v1/scanner/login', [
            'email' => $user->email,
            'password' => 'secret123',
        ])->assertUnprocessable()->assertJsonValidationErrors(['email']);
    }

    public function test_an_invalid_password_is_recorded_with_the_users_tenant(): void
    {
        $role = Role::query()->create([
            'codigo' => RoleCode::Scanner->value,
            'nombre' => 'Scanner',
        ]);
        $permission = Permission::query()->create([
            'codigo' => PermissionCode::ScanTickets->value,
            'nombre' => 'Escanear tickets',
        ]);
        $role->permissions()->attach($permission->codigo);
        $tenant = Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.test',
        ]);
        $user = User::factory()->create([
            'email' => 'scanner@example.com',
            'password' => Hash::make('correct-password'),
            'rol_codigo' => $role->codigo,
            'tenant_codigo' => $tenant->codigo,
        ]);

        $this->postJson('/api/v1/scanner/login', [
            'email' => $user->email,
            'password' => 'wrong-password',
        ])->assertUnprocessable()->assertJsonValidationErrors(['email']);

        $this->assertSame(1, $user->refresh()->failed_login_attempts);
        $this->assertDatabaseHas('login_attempts', [
            'user_id' => $user->id,
            'tenant_codigo' => $tenant->codigo,
            'outcome' => LoginAttempt::OUTCOME_INVALID_CREDENTIALS,
        ]);
    }

    public function test_locking_a_scanner_sends_the_scanner_password_reset_flow(): void
    {
        Event::fake([PasswordResetRequested::class]);
        config([
            'login-security.max_attempts' => 3,
            'login-security.rate_limit_per_minute' => 100,
            'login-security.ip_rate_limit_per_minute' => 100,
        ]);
        $role = Role::query()->create([
            'codigo' => RoleCode::Scanner->value,
            'nombre' => 'Scanner',
        ]);
        $permission = Permission::query()->create([
            'codigo' => PermissionCode::ScanTickets->value,
            'nombre' => 'Escanear tickets',
        ]);
        $role->permissions()->attach($permission->codigo);
        $tenant = Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.test',
        ]);
        $user = User::factory()->create([
            'email' => 'scanner@example.com',
            'password' => Hash::make('correct-password'),
            'rol_codigo' => $role->codigo,
            'tenant_codigo' => $tenant->codigo,
        ]);
        $payload = [
            'email' => $user->email,
            'password' => 'wrong-password',
        ];

        $this->postJson('/api/v1/scanner/login', $payload)->assertUnprocessable();
        $this->postJson('/api/v1/scanner/login', $payload)->assertUnprocessable();
        $this->postJson('/api/v1/scanner/login', $payload)->assertTooManyRequests();

        $attempt = $user->resetPasswordAttempts()->sole();
        $this->assertSame(ResetPasswordAttempt::REASON_ACCOUNT_LOCKED, $attempt->reason);
        Event::assertDispatched(
            PasswordResetRequested::class,
            fn (PasswordResetRequested $event): bool => $event->attemptId === $attempt->id
                && $event->tenantCode === $tenant->codigo
                && $event->channel === PasswordResetRequested::CHANNEL_SCANNER,
        );
    }
}
