<?php

namespace App\VehicleSpec\Services;

use App\Facades\Settings;
use App\TaxonomyMap;
use App\Traits\MapsTaxonomies;
use Mtc\MercuryDataModels\Vehicle;

class CapSectorBodyTypeService
{
    use MapsTaxonomies;

    private ?Vehicle $currentVehicle = null;

    public function __construct(
        private readonly Cap $capService,
        private readonly CapSectorMapper $mapper
    ) {
    }

    /**
     * Look up the CAP sector for the vehicle and, if a matching body_style is
     * found in the taxonomy, update the vehicle. Returns true when
     * body_style_id was updated.
     */
    public function applyForVehicle(Vehicle $vehicle): bool
    {
        if (!Settings::get('vehicle-spec-providers-cap-use-sector-for-body-type')) {
            return false;
        }
        if (empty($vehicle->cap_id)) {
            return false;
        }

        $this->currentVehicle = $vehicle;

        $sector = $this->capService->getSectorForCapId($vehicle);
        if (empty($sector)) {
            return false;
        }

        $bodyStyleId = null;
        foreach ($this->mapper->candidates($sector) as $candidate) {
            $bodyStyleId = $this->getMappedTaxonomy(
                TaxonomyMap::BODY_STYLE,
                $candidate,
                ['registration_number' => $vehicle->registration_number ?? '']
            );
            if (!empty($bodyStyleId)) {
                break;
            }
        }

        $this->storeUnmappedTaxonomy($vehicle);

        if (empty($bodyStyleId)) {
            return false;
        }
        if ((int)$vehicle->body_style_id === (int)$bodyStyleId) {
            return false;
        }

        $vehicle->update(['body_style_id' => $bodyStyleId]);
        return true;
    }

    protected function getProviderName(): string
    {
        return 'cap';
    }

    protected function getDetailsForTaxonomyMap(array $record)
    {
        return [
            'tenant_id' => tenant('id'),
            'registration_number' => $this->currentVehicle?->registration_number ?? '',
        ];
    }
}
