<?php

use App\Livewire\Studio\Catalog\Bottle\Index;
use App\Models\Bottle;
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 bottle']);
    Permission::firstOrCreate(['name' => 'delete bottle']);
    $role->givePermissionTo(['view bottle', 'delete bottle']);
    $this->user->assignRole($role);
});

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

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

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

    $this->assertSoftDeleted('bottles', ['id' => $bottle->id]);
});

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

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