<?php

namespace Tests\Feature;

use App\Models\Product;
use App\Models\Category;
use App\Models\StockMovement;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ProductStockTest extends TestCase
{
    use RefreshDatabase;

    public function test_product_stock_updates_automatically_when_stock_movement_created()
    {
        // Create a category and product
        $category = Category::factory()->create();
        $product = Product::factory()->create([
            'category_id' => $category->id,
            'current_stock' => 0
        ]);

        // Create a stock movement
        StockMovement::create([
            'product_id' => $product->id,
            'type' => 'in',
            'quantity' => 10,
            'reference' => 'Initial stock',
            'created_by' => 1
        ]);

        // Refresh the product and check stock
        $product->refresh();
        $this->assertEquals(10, $product->current_stock);
    }

    public function test_product_available_stock_considers_reservations()
    {
        $category = Category::factory()->create();
        $product = Product::factory()->create([
            'category_id' => $category->id,
            'current_stock' => 20
        ]);

        // Create a stock reservation
        $product->stockReservations()->create([
            'quantity' => 5,
            'status' => 'pending',
            'expires_at' => now()->addMinutes(5),
            'reference' => 'test-order'
        ]);

        $this->assertEquals(15, $product->available_stock);
    }

    public function test_stock_calculation_performance()
    {
        $category = Category::factory()->create();
        $product = Product::factory()->create([
            'category_id' => $category->id,
            'current_stock' => 0
        ]);

        // Create multiple stock movements
        for ($i = 0; $i < 100; $i++) {
            StockMovement::create([
                'product_id' => $product->id,
                'type' => 'in',
                'quantity' => 1,
                'reference' => "Movement $i",
                'created_by' => 1
            ]);
        }

        // Measure time for stock access
        $start = microtime(true);
        $stock = $product->current_stock;
        $end = microtime(true);

        // Should be fast (less than 10ms)
        $this->assertLessThan(0.01, $end - $start);
        $this->assertEquals(100, $stock);
    }
}