<?php

use App\Livewire\Studio\Catalog\Bottle\Edit;
use App\Models\Bottle;
use App\Models\Outlet;
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' => 'update bottle']);
    $role->givePermissionTo(['view bottle', 'update bottle']);
    $this->user->assignRole($role);
});

it('renders the bottle edit page correctly', function () {
    $bottle = Bottle::factory()->create();

    $this->actingAs($this->user)
        ->get(route('studio.catalog.bottle.edit', ['bottle' => $bottle]))
        ->assertOk()
        ->assertSeeLivewire(Edit::class);
});

it('can load data correctly into edit form', function () {
    $bottle = Bottle::factory()->create(['name' => 'Old Bottle Name']);

    Livewire::actingAs($this->user)
        ->test(Edit::class, ['bottle' => $bottle])
        ->assertSet('form.name', 'Old Bottle Name')
        ->assertSet('form.bottle.id', $bottle->id);
});

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

    Livewire::actingAs($this->user)
        ->test(Edit::class, ['bottle' => $bottle])
        ->set('form.name', 'Updated Bottle Name')
        ->set('form.outlet_ids', [$outlet->id])
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.catalog.bottle.index', ['notification' => 'Botol berhasil diperbarui.']));

    $this->assertDatabaseHas('bottles', [
        'id' => $bottle->id,
        'name' => 'Updated Bottle Name',
    ]);
});

it('cannot access bottle edit without permission', function () {
    $bottle = Bottle::factory()->create();
    $this->user->roles()->detach();
    $this->user->permissions()->detach();

    $this->actingAs($this->user)
        ->get(route('studio.catalog.bottle.edit', ['bottle' => $bottle]))
        ->assertForbidden();
});
