<?php

namespace App\Filament\Resources\PurchaseOrderResource\Pages;

use App\Filament\Resources\PurchaseOrderResource;
use App\Models\Purchasing\PurchaseOrder;
use App\Services\PurchaseOrderService;
use Filament\Resources\Pages\CreateRecord;

class CreatePurchaseOrder extends CreateRecord
{
    protected static string $resource = PurchaseOrderResource::class;

    /**
     * Routed entirely through PurchaseOrderService::create() (po_number
     * generation, item creation, audit log) rather than a plain
     * Eloquent create — matches the source controller's store() exactly,
     * which never calls PurchaseOrder::create() directly itself.
     */
    protected function handleRecordCreation(array $data): PurchaseOrder
    {
        PurchaseOrderResource::assertBranchAccessible((int) $data['branch_id']);

        return app(PurchaseOrderService::class)->create(
            header: [
                'supplier_id' => (int) $data['supplier_id'],
                'branch_id' => (int) $data['branch_id'],
                'expected_date' => $data['expected_date'] ?? null,
                'notes' => $data['notes'] ?? null,
            ],
            lines: array_map(fn (array $item): array => [
                'product_id' => (int) $item['product_id'],
                'unit_id' => isset($item['unit_id']) ? (int) $item['unit_id'] : null,
                'quantity' => (float) $item['quantity'],
                'unit_cost' => isset($item['unit_cost']) ? (float) $item['unit_cost'] : null,
            ], $data['items']),
        );
    }
}
