<?php

namespace Tests\Unit\Services\Inventory;

use App\Services\Inventory\InventoryContextService;
use App\Services\Inventory\InventoryItemService;
use App\Services\Inventory\InventoryMovementService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class InventoryItemServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_create_creates_item_and_movement(): void
    {
        $this->seedConfig();
        $categoryId = $this->seedCategory();
        $service = new InventoryItemService(new InventoryContextService(), new InventoryMovementService(new InventoryContextService()));

        $result = $service->create([
            'type' => 'classroom',
            'category_id' => $categoryId,
            'name' => 'Markers',
            'quantity' => 2,
        ]);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('inventory_items', ['name' => 'Markers']);
        $this->assertDatabaseHas('inventory_movements', ['movement_type' => 'initial']);
    }

    public function test_update_updates_item(): void
    {
        $this->seedConfig();
        $categoryId = $this->seedCategory();
        $itemId = $this->seedItem($categoryId);
        $service = new InventoryItemService(new InventoryContextService(), new InventoryMovementService(new InventoryContextService()));

        $result = $service->update($itemId, ['name' => 'Updated'], 1);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('inventory_items', ['id' => $itemId, 'name' => 'Updated']);
    }

    private function seedConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);
    }

    private function seedCategory(): int
    {
        return DB::table('inventory_categories')->insertGetId([
            'type' => 'classroom',
            'name' => 'Classroom',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedItem(int $categoryId): int
    {
        return DB::table('inventory_items')->insertGetId([
            'type' => 'classroom',
            'category_id' => $categoryId,
            'name' => 'Item',
            'quantity' => 1,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
