<?php

namespace App\Filament\Resources\GrnResource\Pages;

use App\Filament\Resources\GrnResource;
use App\Models\Inventory\Grn;
use App\Services\GrnService;
use App\Support\SerialInput;
use Filament\Resources\Pages\CreateRecord;

class CreateGrn extends CreateRecord
{
    protected static string $resource = GrnResource::class;

    /**
     * Routed entirely through GrnService::create() — matches the source
     * controller's store(), which never calls Grn::create() directly.
     */
    protected function handleRecordCreation(array $data): Grn
    {
        GrnResource::assertBranchAccessible((int) $data['branch_id']);

        $mainCategoryId = isset($data['main_category_id']) ? (int) $data['main_category_id'] : null;

        GrnResource::assertItemsMatchCategory($mainCategoryId, $data['items']);

        return app(GrnService::class)->create(
            header: [
                'branch_id' => (int) $data['branch_id'],
                'supplier_id' => isset($data['supplier_id']) ? (int) $data['supplier_id'] : null,
                'purchase_order_id' => isset($data['purchase_order_id']) ? (int) $data['purchase_order_id'] : null,
                'reference' => $data['reference'] ?? null,
                'note' => $data['note'] ?? 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']) && $item['unit_cost'] !== null ? (float) $item['unit_cost'] : null,
                'sale_price' => isset($item['sale_price']) && $item['sale_price'] !== null ? (float) $item['sale_price'] : null,
                'expiry_date' => $item['expiry_date'] ?? null,
                'manufacture_date' => $item['manufacture_date'] ?? null,
                'batch_cost' => isset($item['batch_cost']) && $item['batch_cost'] !== null && $item['batch_cost'] !== ''
                    ? (float) $item['batch_cost'] : null,
                'serial_numbers' => ! empty($item['serial_numbers'])
                    ? SerialInput::numbers($item['serial_numbers'])
                    : null,
            ], $data['items']),
        );
    }
}
