<?php

use App\Models\User;
use Livewire\Livewire;
use Modules\Catalog\Filament\Resources\Destinations\Pages\CreateDestination;
use Modules\Catalog\Filament\Resources\Destinations\Pages\EditDestination;
use Modules\Catalog\Filament\Resources\Destinations\Pages\ListDestinations;
use Modules\Catalog\Models\Destination;
use Spatie\Permission\Models\Role;

use function Pest\Laravel\assertDatabaseHas;

beforeEach(function () {
    Role::findOrCreate('admin', 'web');

    $this->admin = User::factory()->create()->assignRole('admin');
    $this->actingAs($this->admin);
});

test('can list destinations', function () {
    $destinations = Destination::factory()->count(3)->create();

    Livewire::test(ListDestinations::class)
        ->assertOk()
        ->assertCanSeeTableRecords($destinations);
});

test('can create a destination', function () {
    $destination = Destination::factory()->make();

    Livewire::test(CreateDestination::class)
        ->fillForm([
            'name' => $destination->name,
            'mm_name' => $destination->mm_name,
            'region' => $destination->region,
            'is_active' => true,
        ])
        ->call('create')
        ->assertNotified()
        ->assertRedirect();

    assertDatabaseHas(Destination::class, [
        'name' => $destination->name,
        'region' => $destination->region,
    ]);
});

test('can edit a destination', function () {
    $destination = Destination::factory()->create();

    Livewire::test(EditDestination::class, ['record' => $destination->getRouteKey()])
        ->assertOk()
        ->fillForm(['name' => 'Updated Name'])
        ->call('save')
        ->assertNotified();

    assertDatabaseHas(Destination::class, [
        'id' => $destination->id,
        'name' => 'Updated Name',
    ]);
});
