<?php

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

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

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

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

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

it('can update a perfume', function () {
    $perfume = Perfume::factory()->create();
    $category = Category::factory()->create();
    $outlet = Outlet::factory()->create();

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

    $this->assertDatabaseHas('perfumes', [
        'id' => $perfume->id,
        'name' => 'Updated Name',
    ]);
});

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

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