<?php

namespace App\Filament\Resources\BarcodeLabelResource\Pages;

use App\Filament\Resources\BarcodeLabelResource;
use App\Models\Inventory\BarcodeLabel;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;
use RuntimeException;

class CreateBarcodeLabel extends CreateRecord
{
    protected static string $resource = BarcodeLabelResource::class;

    protected function handleRecordCreation(array $data): BarcodeLabel
    {
        try {
            $label = BarcodeLabelResource::apply($data);
        } catch (RuntimeException $e) {
            // The service's refusals are all about one field being wrong for
            // the product picked, so they belong on the form, not in a toast
            // that leaves the operator guessing which control to fix.
            throw ValidationException::withMessages([
                'data.product_id' => $e->getMessage(),
            ]);
        }

        AuditLog::record('barcode_label.created', $label, [
            'code' => $label->code,
            'product' => $label->product?->name,
            'lot' => $label->batch?->internal_batch_number,
            'serial' => $label->serial?->serial_number,
            'base_quantity' => (string) $label->base_quantity,
        ]);

        return $label;
    }
}
