<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\VehicleResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Vehicle;

class VehicleController extends Controller
{
    /**
     * Look up a vehicle by VRM (registration number) and return vehicle data.
     */
    public function lookupByVrm(Request $request): VehicleResource|JsonResponse
    {
        $request->validate([
            'vrm' => ['required', 'string', 'max:10'],
        ]);

        $vrm = preg_replace('/\s+/', '', strtoupper($request->input('vrm')));

        $vehicle = Vehicle::query()
            ->where('registration_number', $vrm)
            ->orWhere('vrm_condensed', $vrm)
            ->first();

        if (!$vehicle) {
            return response()->json([
                'message' => 'Vehicle not found.',
            ], 404);
        }

        return new VehicleResource($vehicle);
    }
}
