<?php

use App\Livewire\Studio\Master\Warehouse\Show;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Models\Warehouse;
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 warehouse']);
    $role->givePermissionTo('view warehouse');
    $this->user->assignRole($role);

    $this->warehouse = Warehouse::factory()->create(['name' => 'Gudang Utama']);
});

it('renders the warehouse show page correctly', function () {
    $this->actingAs($this->user)
        ->get(route('studio.master.warehouse.show', $this->warehouse))
        ->assertOk()
        ->assertSeeLivewire(Show::class)
        ->assertSee('Detail Gudang');
});

it('displays correct statistics and items', function () {
    $perfume = Perfume::factory()->create(['name' => 'Parfum ABC']);
    $product = Product::factory()->create(['name' => 'Produk XYZ']);
    $bottle = Bottle::factory()->create(['name' => 'Botol 100ml']);

    $this->warehouse->perfumes()->attach($perfume, ['stock' => 10]);
    $this->warehouse->products()->attach($product, ['stock' => 20]);
    $this->warehouse->bottles()->attach($bottle, ['stock' => 30]);

    Livewire::actingAs($this->user)
        ->test(Show::class, ['warehouse' => $this->warehouse])
        ->assertSee('Parfum ABC')
        ->assertSee('Produk XYZ')
        ->assertSee('Botol 100ml')
        ->assertSee('10') // stock perfume
        ->assertSee('20') // stock product
        ->assertSee('30') // stock bottle
        ->assertViewHas('stats', function ($stats) {
            return $stats[0]['value'] == '3' && // Total Item
                $stats[1]['value'] == '1' && // Parfum
                $stats[2]['value'] == '1' && // Produk
                $stats[3]['value'] == '1';   // Botol
        });
});

it('cannot access show page without permission', function () {
    $this->user->roles()->detach();
    $this->user->permissions()->detach();

    $this->actingAs($this->user)
        ->get(route('studio.master.warehouse.show', $this->warehouse))
        ->assertForbidden();
});
