<?php

use App\Livewire\Studio\Catalog\Perfume\Index;
use App\Models\Perfume;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser();

    $role = Role::firstOrCreate(['name' => 'Owner']);
    Permission::firstOrCreate(['name' => 'view perfume']);
    Permission::firstOrCreate(['name' => 'delete perfume']);
    $role->givePermissionTo(['view perfume', 'delete perfume']);
    $this->user->assignRole($role);
});

it('renders the perfume index page correctly', function () {
    $this->actingAs($this->user)
        ->get(route('studio.catalog.perfume.index'))
        ->assertOk()
        ->assertSeeLivewire(Index::class);
});

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

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->call('delete', $perfume->id)
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

    $this->assertSoftDeleted('perfumes', ['id' => $perfume->id]);
});

it('cannot access perfume index without permission', function () {
    $this->user->roles()->detach();
    $this->user->permissions()->detach();

    $this->actingAs($this->user)
        ->get(route('studio.catalog.perfume.index'))
        ->assertForbidden();
});
