<?php

namespace App\Filament\Resources\ReturnGrnResource\Pages;

use App\Filament\Resources\ReturnGrnResource;
use App\Models\Inventory\ReturnGrn;
use App\Services\ReturnGrnService;
use Filament\Resources\Pages\CreateRecord;

class CreateReturnGrn extends CreateRecord
{
    protected static string $resource = ReturnGrnResource::class;

    /**
     * Routed entirely through ReturnGrnService::create() — a draft with its
     * lines only, no stock effect (mirrors CreateGrn).
     */
    protected function handleRecordCreation(array $data): ReturnGrn
    {
        ReturnGrnResource::assertBranchAccessible((int) $data['branch_id']);

        return app(ReturnGrnService::class)->create(
            header: [
                'branch_id' => (int) $data['branch_id'],
                'supplier_id' => isset($data['supplier_id']) ? (int) $data['supplier_id'] : null,
                'reference' => $data['reference'] ?? null,
                'reason' => $data['reason'] ?? 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,
                'source_grn_item_id' => ! empty($item['source_grn_item_id']) ? (int) $item['source_grn_item_id'] : null,
                'stock_batch_id' => ! empty($item['stock_batch_id']) ? (int) $item['stock_batch_id'] : null,
                'quantity' => (float) $item['quantity'],
                'unit_cost' => isset($item['unit_cost']) && $item['unit_cost'] !== null && $item['unit_cost'] !== ''
                    ? (float) $item['unit_cost'] : null,
                'serial_numbers' => $item['serial_numbers'] ?? null,
            ], $data['items']),
        );
    }
}
