<?php

namespace Tests\Unit\Services;

use App\Models\ProductVariant;
use App\Services\InventoryService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class InventoryServiceTest extends TestCase
{
    use RefreshDatabase;

    private InventoryService $inventory;

    protected function setUp(): void
    {
        parent::setUp();
        $this->inventory = app(InventoryService::class);
    }

    public function test_adjust_increases_stock_and_logs_positive_delta(): void
    {
        $admin = $this->admin();
        $variant = ProductVariant::factory()->withStock(10)->create();

        $this->inventory->adjust($variant, 25, null, 'Restocked', $admin);

        $this->assertSame(25, $variant->inventory->fresh()->quantity);
        $this->assertDatabaseHas('inventory_movements', [
            'product_variant_id' => $variant->id, 'type' => 'adjustment', 'quantity' => 15, 'reason' => 'Restocked', 'created_by' => $admin->id,
        ]);
    }

    public function test_adjust_decreases_stock_and_logs_negative_delta(): void
    {
        $admin = $this->admin();
        $variant = ProductVariant::factory()->withStock(20)->create();

        $this->inventory->adjust($variant, 12, null, null, $admin);

        $this->assertSame(12, $variant->inventory->fresh()->quantity);
        $this->assertDatabaseHas('inventory_movements', ['product_variant_id' => $variant->id, 'quantity' => -8]);
    }

    public function test_adjust_to_same_quantity_creates_no_movement(): void
    {
        $admin = $this->admin();
        $variant = ProductVariant::factory()->withStock(10)->create();

        $this->inventory->adjust($variant, 10, null, null, $admin);

        $this->assertDatabaseCount('inventory_movements', 0);
    }

    public function test_adjust_can_update_the_low_stock_threshold(): void
    {
        $admin = $this->admin();
        $variant = ProductVariant::factory()->withStock(10, 5)->create();

        $this->inventory->adjust($variant, 10, 20, null, $admin);

        $this->assertSame(20, $variant->inventory->fresh()->low_stock_threshold);
    }
}
