<?php

namespace Tests\Feature;

use App\Filament\Pages\Auth\Login;
use App\Models\Role;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Hash;
use Livewire\Livewire;
use Tests\TestCase;

class AdminPinLoginTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Filament::setCurrentPanel('admin');
    }

    public function test_admin_can_authenticate_with_valid_pin(): void
    {
        $user = $this->createAdminUser();
        $this->assertTrue(Hash::check('1234', $user->admin_pin_hash));

        Livewire::test(Login::class)
            ->call('selectUser', $user->id)
            ->assertSet('data.email', $user->email)
            ->call('appendPinDigit', 1)
            ->call('appendPinDigit', 2)
            ->call('appendPinDigit', 3)
            ->call('appendPinDigit', 4)
            ->assertSet('data.pin', '1234')
            ->call('authenticate')
            ->assertHasNoErrors()
            ->assertRedirect(Filament::getUrl());
    }

    public function test_admin_cannot_authenticate_with_invalid_pin(): void
    {
        $user = $this->createAdminUser();

        Livewire::test(Login::class)
            ->call('selectUser', $user->id)
            ->assertSet('data.email', $user->email)
            ->call('appendPinDigit', 0)
            ->call('appendPinDigit', 0)
            ->call('appendPinDigit', 0)
            ->call('appendPinDigit', 0)
            ->assertSet('data.pin', '0000')
            ->call('authenticate')
            ->assertHasErrors(['data.email']);

        $this->assertGuest();
    }

    protected function createAdminUser(): User
    {
        $role = Role::firstOrCreate(['name' => 'Admin']);

        return User::factory()->create([
            'role_id' => $role->id,
            'admin_pin_hash' => Hash::make('1234'),
        ]);
    }
}
