<?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\MotorCheckConfig;
use App\VehicleSpec\Contracts\VehicleSpecProvider;
use App\VehicleSpec\Services\AutoTraderSpecProvider;
use App\VehicleSpec\Services\Cap;
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 ((new self())->determineProvider()) {
            Cap::class => !empty($vehicle->cap_id),
            AutoTraderSpecProvider::class => !empty($vehicle->auto_trader_id),
            MotorCheckSpecProvider::class => !empty($vehicle->registration_number),
            default => false,
        };
    }

    /**
     * @return VehicleSpecProvider
     */
    protected function initialize(): ?VehicleSpecProvider
    {
        // load relevant provider with config
        return match ($this->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),
            ),
            '' => null
        };
    }

    /**
     * Determine which provider is set for the client
     *
     * @return string
     */
    protected 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;
        }

        return '';
    }
}
