<?php

namespace Tests\Feature;

use App\Models\Divisi;
use App\Models\Item;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ItemManagementCrudTest extends TestCase
{
    use RefreshDatabase;

    public function test_authenticated_user_can_view_item_index_and_show_page(): void
    {
        $divisi = Divisi::create(['nama' => 'Divisi Item']);
        $user = User::factory()->create(['role' => 'user']);
        $item = Item::create([
            'nama' => 'Modem',
            'sku' => 'MDM-001',
            'jumlah' => 6,
            'min_stok' => 1,
            'divisi_id' => $divisi->id,
        ]);

        $this->actingAs($user)->get(route('items.index'))->assertOk();
        $this->actingAs($user)->get(route('items.show', $item))->assertOk();
    }

    public function test_staff_can_update_item(): void
    {
        $divisi = Divisi::create(['nama' => 'Divisi Update']);
        $staff = User::factory()->create(['role' => 'staff_bidang', 'divisi_id' => $divisi->id]);
        $item = Item::create([
            'nama' => 'Router',
            'sku' => 'RTR-001',
            'jumlah' => 3,
            'min_stok' => 1,
            'divisi_id' => $divisi->id,
        ]);

        $response = $this->actingAs($staff)->put(route('items.update', $item), [
            'nama' => 'Router Baru',
            'sku' => 'RTR-001',
            'deskripsi' => 'Updated',
            'divisi_id' => $divisi->id,
            'jumlah' => 7,
            'min_stok' => 2,
        ]);

        $response->assertRedirect(route('items.index'));
        $this->assertDatabaseHas('items', [
            'id' => $item->id,
            'nama' => 'Router Baru',
            'jumlah' => 7,
        ]);
    }

    public function test_staff_can_delete_item(): void
    {
        $divisi = Divisi::create(['nama' => 'Divisi Delete']);
        $staff = User::factory()->create(['role' => 'staff_bidang', 'divisi_id' => $divisi->id]);
        $item = Item::create([
            'nama' => 'Switch',
            'sku' => 'SWT-001',
            'jumlah' => 3,
            'min_stok' => 1,
            'divisi_id' => $divisi->id,
        ]);

        $response = $this->actingAs($staff)->delete(route('items.destroy', $item));

        $response->assertRedirect(route('items.index'));
        $this->assertDatabaseMissing('items', ['id' => $item->id]);
    }
}
