<?php

namespace Tests\Feature;

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

class PurchaseOrderApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_purchase_order_create_and_receive_updates_stock(): void
    {
        ['company' => $company, 'user' => $user, 'branch' => $branch] = $this->createUserWithPermissions([
            'purchases.view',
            'purchases.manage',
            'purchases.receive',
        ]);

        $product = Product::factory()->create([
            'company_id' => $company->id,
            'name' => 'Sugar 2kg',
            'sku' => 'SGR2KG',
            'selling_price' => 250,
        ]);

        $supplier = Supplier::factory()->create([
            'company_id' => $company->id,
        ]);

        $create = $this->actingAsApi($user, $branch->id)
            ->postJson('/api/v1/purchase-orders', [
                'supplier_id' => $supplier->id,
                'order_date' => now()->toDateString(),
                'items' => [
                    [
                        'product_id' => $product->id,
                        'quantity_ordered' => 8,
                        'unit_cost' => 150,
                    ],
                ],
            ]);

        $create->assertCreated();
        $purchaseOrderId = $create->json('data.id');
        $purchaseOrderItemId = $create->json('data.items.0.id');

        $receive = $this->actingAsApi($user, $branch->id)
            ->postJson("/api/v1/purchase-orders/{$purchaseOrderId}/receive", [
                'items' => [
                    [
                        'purchase_order_item_id' => $purchaseOrderItemId,
                        'quantity_received' => 8,
                        'batch_number' => 'BATCH-001',
                    ],
                ],
            ]);

        $receive->assertOk()
            ->assertJsonPath('data.status', 'received');

        $stock = StockLevel::query()
            ->where('branch_id', $branch->id)
            ->where('product_id', $product->id)
            ->first();

        $this->assertNotNull($stock);
        $this->assertSame('8.0000', $stock->quantity);
    }
}
