<?php

use App\Livewire\Studio\Manage\Restock\Index;
use App\Models\Perfume;
use App\Models\Restock;
use App\Models\Warehouse;
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 restock',
        'delete restock',
    ];

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

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

it('renders the restock index page', function () {
    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->assertStatus(200);
});

it('can delete a restock and reverse stock transfer', function () {
    $warehouse = Warehouse::factory()->create();
    $perfume = Perfume::factory()->create();

    // Initial state: Warehouse 90, Outlet 10 (simulating after a restock of 10)
    $warehouse->perfumes()->attach($perfume->id, ['stock' => 90]);
    $this->outlet->perfumes()->attach($perfume->id, ['stock' => 10]);

    $restock = Restock::create([
        'warehouse_id' => $warehouse->id,
        'outlet_id' => $this->outlet->id,
        'restock_date' => now(),
        'note' => 'To be deleted',
    ]);

    $restock->items()->create([
        'user_id' => $this->user->id,
        'restockable_type' => Perfume::class,
        'restockable_id' => $perfume->id,
        'quantity' => 10,
    ]);

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->call('delete', $restock->id);

    $this->assertSoftDeleted('restocks', ['id' => $restock->id]);

    // Verify Stock Reversal
    $this->assertEquals(100, $warehouse->perfumes()->find($perfume->id)->pivot->stock); // 90 + 10
    $this->assertEquals(0, $this->outlet->perfumes()->find($perfume->id)->pivot->stock); // 10 - 10
});
