<?php

use App\Enums\StockOpnameStatus;
use App\Livewire\Studio\Manage\StockOpname\Manage;
use App\Models\Perfume;
use App\Models\StockOpname;
use App\Models\StockOpnameItem;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser();
    $this->outlet = $this->user->outlets->first();

    // Create permissions
    $permissions = [
        'view stock opname',
        'manage stock opname',
    ];

    foreach ($permissions as $permission) {
        Permission::firstOrCreate(['name' => $permission]);
    }

    $role = Role::create(['name' => 'Owner']);
    $role->givePermissionTo($permissions);
    $this->user->assignRole($role);
});

it('can update physical quantity in manage page', function () {
    // Create pre-existing StockOpname
    $stockOpname = StockOpname::create([
        'outlet_id' => $this->outlet->id,
        'period_month' => now()->format('Y-m'),
        'status' => StockOpnameStatus::PROCESS,
    ]);

    $perfume = Perfume::factory()->create();
    $item = StockOpnameItem::create([
        'stock_opname_id' => $stockOpname->id,
        'user_id' => $this->user->id,
        'itemable_type' => Perfume::class,
        'itemable_id' => $perfume->id,
        'qty_system' => 10,
    ]);

    Livewire::actingAs($this->user)
        ->test(Manage::class, ['stockOpname' => $stockOpname])
        ->set('form.outlet_stock.'.$item->id, 8) // Physical count is 8
        ->assertSet('form.outlet_stock.'.$item->id, 8);

    $this->assertDatabaseHas('stock_opname_items', [
        'id' => $item->id,
        'qty_physical' => 8,
    ]);
});

it('cannot manage stock opname if not in process status', function () {
    $stockOpname = StockOpname::create([
        'outlet_id' => $this->outlet->id,
        'period_month' => now()->format('Y-m'),
        'status' => StockOpnameStatus::COMPLETED,
    ]);

    Livewire::actingAs($this->user)
        ->test(Manage::class, ['stockOpname' => $stockOpname])
        ->assertForbidden();
});
