<?php

use App\Filament\Resources\UserResource\Pages\EditUser;
use App\Filament\Resources\UserResource\Pages\ListUsers;
use App\Models\User;
use Filament\Actions\DeleteAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->admin = User::factory()->admin()->create();
    $this->actingAs($this->admin);
});

it('renders the user list', function () {
    $users = User::factory()->count(3)->create();

    Livewire::test(ListUsers::class)
        ->assertOk()
        ->assertCanSeeTableRecords($users);
});

it('can toggle is_admin on edit', function () {
    $user = User::factory()->create(['is_admin' => false]);

    Livewire::test(EditUser::class, ['record' => $user->id])
        ->fillForm(['is_admin' => true])
        ->call('save')
        ->assertHasNoFormErrors();

    expect($user->fresh()->is_admin)->toBeTrue();
});

it('can delete a user', function () {
    $user = User::factory()->create();

    Livewire::test(ListUsers::class)
        ->callTableAction(DeleteAction::class, $user)
        ->assertHasNoTableActionErrors();

    $this->assertDatabaseMissing('users', ['id' => $user->id]);
});
