<?php

namespace Tests\Unit\Services\PurchaseOrders;

use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\Supply;
use App\Services\PurchaseOrders\PurchaseOrderReceiveService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PurchaseOrderReceiveServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_receive_updates_items_and_inventory(): void
    {
        $supply = Supply::query()->create([
            'name' => 'Paper',
            'unit' => 'box',
            'qty_on_hand' => 2,
        ]);

        $po = PurchaseOrder::query()->create([
            'po_number' => 'PO-600',
            'supplier_id' => 1,
            'status' => PurchaseOrder::STATUS_ORDERED,
            'subtotal' => 10,
            'tax' => 0,
            'total' => 10,
        ]);

        $item = PurchaseOrderItem::query()->create([
            'purchase_order_id' => $po->id,
            'supply_id' => $supply->id,
            'description' => 'Paper for class',
            'quantity' => 3,
            'received_qty' => 0,
            'unit_cost' => 3,
        ]);

        $service = new PurchaseOrderReceiveService();
        $result = $service->receive($po->id, [
            ['id' => $item->id, 'quantity' => 3],
        ], 'tester@example.com');

        $this->assertTrue($result['completed']);
        $this->assertDatabaseHas('purchase_order_items', [
            'id' => $item->id,
            'received_qty' => 3,
        ]);
        $this->assertDatabaseHas('supplies', [
            'id' => $supply->id,
            'qty_on_hand' => 5,
        ]);
        $this->assertDatabaseHas('supply_transactions', [
            'supply_id' => $supply->id,
            'type' => 'in',
            'quantity' => 3,
        ]);
    }
}
