<?php

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

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

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

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

    $this->assertSoftDeleted('products', ['id' => $product->id]);
});

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

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