<?php

namespace App\Http\Resources\VehicleAction;

use App\Facades\Settings;
use App\Facades\Site;
use App\IntegrationRepository;
use App\Sales\SilverBullet;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Vehicle;

class DealFactory
{
    public function get(Vehicle $vehicle)
    {
        if ($this->hasKeyloopValuation()) {
            return App::make(SilverBullet::class)->getVehicleAction($vehicle, 'deal');
        }

        if ($this->hasCodeWeaversEnabled() && $vehicle->defaultFinanceExample?->apply_url) {
            return $this->codeWeaversWidget($vehicle);
        }

        return false;
    }

    private function hasKeyloopValuation(): bool
    {
        return Settings::get('sales-silver-bullet-enabled')
            && Settings::get('sales-silver-bullet-build-deal');
    }

    private function hasCodeWeaversEnabled(): bool
    {
        return Settings::get('sales-codeweavers-build-deal')
            && (new IntegrationRepository())->getEnabledForType('finance')
                ->keys()
                ->first() === 'code-weavers';
    }

    private function codeWeaversWidget(Vehicle $vehicle): array
    {
        return [
            'type' => 'component',
            'value' => 'CatalogCodeWeaversDeal',
            'data' => [
                'action' => 'deal',
                'url' => $vehicle->defaultFinanceExample?->apply_url,
                'title' => Settings::get('sales-codeweavers-deal-button-text'),
                'api_key' => Settings::get('finance-codeweavers-api_key'),
                'quote_id' => str_replace(
                    ['https://services.codeweavers.net/forms/quote/', '/apply'],
                    '',
                    $vehicle->defaultFinanceExample?->apply_url
                ),
                'id' => $vehicle->id,
                'vehicle_id' => $vehicle-> uuid ?? $vehicle->id,
                'dealer_id' => $vehicle->dealership->data['codeweavers']
                    ?? Settings::get('finance-codeweavers-dealer_name'),
                'vehicle_url' => Site::vehicleUrl($vehicle),
            ],
        ];
    }
}
