<?php

namespace Tests\Unit\Services\PurchaseOrders;

use App\Services\PurchaseOrders\PurchaseOrderCreateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class PurchaseOrderCreateServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_create_persists_purchase_order_and_items(): void
    {
        $supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
        $supplyId = DB::table('supplies')->insertGetId(['name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 0]);

        $service = new PurchaseOrderCreateService();
        $po = $service->create([
            'po_number' => 'PO-500',
            'supplier_id' => $supplierId,
            'order_date' => '2026-03-10',
            'expected_date' => '2026-03-15',
            'notes' => 'Initial order',
            'items' => [
                [
                    'supply_id' => $supplyId,
                    'description' => 'Paper for class',
                    'quantity' => 3,
                    'unit_cost' => 4,
                ],
            ],
        ]);

        $this->assertNotNull($po->id);
        $this->assertDatabaseHas('purchase_orders', [
            'id' => $po->id,
            'po_number' => 'PO-500',
            'subtotal' => 12,
            'total' => 12,
        ]);
        $this->assertDatabaseHas('purchase_order_items', [
            'purchase_order_id' => $po->id,
            'supply_id' => $supplyId,
            'quantity' => 3,
            'unit_cost' => 4,
        ]);
    }
}
