<?php

namespace Tests\Feature;

use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class InventoryApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_product_creation_and_stock_adjustment_flow(): void
    {
        ['company' => $company, 'user' => $user, 'branch' => $branch] = $this->createUserWithPermissions([
            'products.view',
            'products.manage',
            'stock.view',
            'stock.adjust',
        ]);

        $productResponse = $this->actingAsApi($user, $branch->id)
            ->postJson('/api/v1/products', [
                'name' => 'Coca Cola 500ml',
                'slug' => 'coca-cola-500ml',
                'sku' => 'COKE500',
                'type' => 'simple',
                'cost_price' => 50,
                'selling_price' => 80,
                'track_stock' => true,
            ]);

        $productResponse->assertCreated();
        $productId = $productResponse->json('data.id');

        $product = Product::findOrFail($productId);
        $this->assertSame($company->id, $product->company_id);

        $adjustment = $this->actingAsApi($user, $branch->id)
            ->postJson('/api/v1/stock-adjustments', [
                'product_id' => $productId,
                'quantity' => 12,
                'type' => 'opening_stock',
                'notes' => 'Initial stock',
            ]);

        $adjustment->assertCreated()
            ->assertJsonPath('data.quantity', '12.0000');

        $listing = $this->actingAsApi($user, $branch->id)
            ->getJson('/api/v1/stock-levels');

        $listing->assertOk()
            ->assertJsonPath('data.0.product_id', $productId);
    }
}
