<?php

namespace Tests\Feature\Filament;

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

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

        Filament::setCurrentPanel('admin');
    }

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

        Livewire::test(EditProfile::class)
            ->set('data.admin_pin', '4321')
            ->call('save')
            ->assertHasNoErrors();

        $user->refresh();

        $this->assertTrue(Hash::check('4321', $user->admin_pin_hash));
    }

    public function test_admin_can_remove_pin_from_profile(): void
    {
        $user = $this->createAdminUser([
            'admin_pin_hash' => Hash::make('5678'),
        ]);
        $this->actingAs($user);

        Livewire::test(EditProfile::class)
            ->set('data.remove_admin_pin', true)
            ->call('save')
            ->assertHasNoErrors();

        $user->refresh();

        $this->assertNull($user->admin_pin_hash);
    }

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

        return User::factory()->create(array_merge([
            'role_id' => $role->id,
        ], $overrides));
    }
}
