<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcRmiLookup;
use Modules\Vrc\Entities\VrcVehicle;
use Modules\Vrc\Services\Contracts\RepairInfoServiceContract;

/**
 * Phase 5 — ISO 18541 Repair & Maintenance Information. VIN decode + use-case
 * lookups go through the bound RepairInfoServiceContract (offline stub by default)
 * and every query is logged to vrc_rmi_lookups for auditability.
 */
class RmiController extends VrcBaseController
{
    public function index()
    {
        $this->guard('vrc.rmi.view');
        $bid = $this->businessId();

        $vehicles = VrcVehicle::where('business_id', $bid)->where('is_active', true)
            ->orderByDesc('id')->limit(500)
            ->get(['id', 'plate_number', 'vin', 'year'])
            ->mapWithKeys(fn ($v) => [$v->id => trim(($v->plate_number ?: 'Vehicle #' . $v->id) . ($v->vin ? " · {$v->vin}" : ''))])
            ->toArray();

        $recent = VrcRmiLookup::where('business_id', $bid)->orderByDesc('id')->limit(20)->get();
        $provider = app(RepairInfoServiceContract::class)->provider();

        return view('vrc::rmi.index', compact('vehicles', 'recent', 'provider'));
    }

    public function decodeVin(Request $request, RepairInfoServiceContract $rmi)
    {
        $this->guard('vrc.rmi.view');
        $data = $this->validate($request, ['vin' => 'required|string|max:40', 'vehicle_id' => 'nullable|integer']);

        $result = $rmi->decodeVin($data['vin']);
        $this->log('vin_decode', $data['vin'], $result, $data['vehicle_id'] ?? null, $rmi->provider());

        return response()->json(['success' => true, 'result' => $result]);
    }

    public function lookup(Request $request, RepairInfoServiceContract $rmi)
    {
        $this->guard('vrc.rmi.view');
        $data = $this->validate($request, [
            'use_case'   => 'required|string|max:30',
            'vehicle_id' => 'nullable|integer',
            'make'       => 'nullable|string|max:120',
            'model'      => 'nullable|string|max:120',
            'year'       => 'nullable|string|max:10',
            'query'      => 'nullable|string|max:255',
        ]);

        $result = $rmi->lookup($data['use_case'], $data);
        $this->log($data['use_case'], $data['query'] ?? '', $result, $data['vehicle_id'] ?? null, $rmi->provider());

        return response()->json(['success' => true, 'result' => $result]);
    }

    private function log(string $useCase, string $query, array $result, ?int $vehicleId, string $provider): void
    {
        VrcRmiLookup::create([
            'business_id' => $this->businessId(),
            'vehicle_id'  => $vehicleId,
            'provider'    => $provider,
            'vin'         => $result['vin'] ?? null,
            'use_case'    => $useCase,
            'query'       => $query,
            'response'    => json_encode($result),
            'status'      => $result['status'] ?? 'ok',
            'created_by'  => $this->userId(),
            'created_at'  => now(),
        ]);
    }
}
