<?php

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

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

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

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

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

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

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

    $this->assertDatabaseHas('products', [
        'id' => $product->id,
        'name' => 'Updated Product Name',
    ]);
});

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

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