<?php

namespace App\VehicleSpec;

use App\Facades\Settings;
use App\Services\AutoTraderApi;
use App\VehicleSpec\Config\AutoTraderConfig;
use App\VehicleSpec\Config\CapConfig;
use App\VehicleSpec\Config\HPIConfig;
use App\VehicleSpec\Config\MotorCheckConfig;
use App\VehicleSpec\Contracts\VehicleSpecProvider;
use App\VehicleSpec\Services\AutoTraderSpecProvider;
use App\VehicleSpec\Services\Cap;
use App\VehicleSpec\Services\HPISpecProvider;
use App\VehicleSpec\Services\MotorCheckSpecProvider;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Vehicle;

class VehicleSpecServiceHelper
{
    /**
     * Call provider initialization (static)
     *
     * @return VehicleSpecProvider
     */
    public static function initializeForSite(): ?VehicleSpecProvider
    {
        return (new self())->initialize();
    }

    public static function canRunForVehicle(Vehicle $vehicle): bool
    {
        return match (self::determineProvider()) {
            Cap::class => !empty($vehicle->cap_id),
            AutoTraderSpecProvider::class => !empty($vehicle->auto_trader_id),
            MotorCheckSpecProvider::class => !empty($vehicle->registration_number),
            HPISpecProvider::class => !empty($vehicle->registration_number),
            default => false,
        };
    }

    /**
     * Determine which provider is set for the client
     *
     * @return string
     */
    public static function determineProvider(): string
    {
        if (Settings::get('vehicle-spec-providers-cap-enabled')) {
            return Cap::class;
        }

        if (Settings::get('vehicle-spec-providers-autotrader-enabled')) {
            return AutoTraderSpecProvider::class;
        }

        if (Settings::get('vehicle-spec-providers-motor-check-enabled')) {
            return MotorCheckSpecProvider::class;
        }

        if (Settings::get('vehicle-spec-providers-hpi-enabled')) {
            return HPISpecProvider::class;
        }

        return '';
    }

    /**
     * @return VehicleSpecProvider
     */
    protected function initialize(): ?VehicleSpecProvider
    {
        // load relevant provider with config
        return match (self::determineProvider()) {
            Cap::class => new Cap(App::make(CapConfig::class)),
            AutoTraderSpecProvider::class => new AutoTraderSpecProvider(
                App::make(AutoTraderConfig::class),
                App::make(AutoTraderApi::class),
            ),
            MotorCheckSpecProvider::class => new MotorCheckSpecProvider(
                App::make(MotorCheckConfig::class),
            ),
            HPISpecProvider::class => new HPISpecProvider(App::make(HPIConfig::class)),
            '' => null
        };
    }
}
