<?php

namespace App\VehicleSpec\Services;

use App\Facades\Settings;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\CapIdCache;
use Mtc\MercuryDataModels\Vehicle;

class LocalVehicleCapIdCacheService
{
    public function lookup(Vehicle $vehicle): ?array
    {
        if (!Settings::get('cap-id-lookup-local-cache-enabled')) {
            return null;
        }

        if (empty($vehicle->derivative)) {
            return null;
        }

        $query = CapIdCache::query()
            ->where('derivative', $vehicle->derivative);

        if ($vehicle->make_id) {
            $query->where('make_id', $vehicle->make_id);
        } else {
            $query->whereNull('make_id');
        }

        if ($vehicle->model_id) {
            $query->where('model_id', $vehicle->model_id);
        } else {
            $query->whereNull('model_id');
        }

        $match = $query->first();

        if (!$match) {
            return null;
        }

        Log::info('CAP ID resolved from local vehicle cache', [
            'tenant' => tenant('id'),
            'vehicle_id' => $vehicle->id,
            'cap_id' => $match->cap_id,
        ]);

        return array_filter([
            'cap_id' => $match->cap_id,
            'cap_code' => $match->cap_code,
            'make_id' => $match->cap_matched_make_id,
            'model_id' => $match->cap_matched_model_id,
            'fuel_type_id' => $match->cap_matched_fuel_type_id,
            'body_style_id' => $match->cap_matched_body_style_id,
            'transmission_id' => $match->cap_matched_transmission_id,
        ]);
    }

    public function store(array $result): void
    {
        if (!Settings::get('cap-id-lookup-local-cache-enabled')) {
            return;
        }

        if (empty($result['cap_id']) || empty($result['derivative'])) {
            return;
        }

        $matchKeys = [
            'make_id' => $result['make_id'] ?? null,
            'model_id' => $result['model_id'] ?? null,
            'derivative' => $result['derivative'],
        ];

        CapIdCache::query()->updateOrCreate(
            $matchKeys,
            [
                'cap_id' => $result['cap_id'],
                'cap_code' => $result['cap_code'] ?? null,
                'cap_matched_make_id' => $result['cap_matched_make_id'] ?? null,
                'cap_matched_model_id' => $result['cap_matched_model_id'] ?? null,
                'cap_matched_fuel_type_id' => $result['cap_matched_fuel_type_id'] ?? null,
                'cap_matched_body_style_id' => $result['cap_matched_body_style_id'] ?? null,
                'cap_matched_transmission_id' => $result['cap_matched_transmission_id'] ?? null,
            ]
        );
    }
}
