<?php

namespace App\Http\Resources\VehicleAction;

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

class ReserveFactory
{
    public function get(Vehicle $vehicle)
    {
        if ($vehicle->is_sold) {
            return false;
        }

        if ($this->hasPaymentReservation()) {
            return App::make(ReservationRepository::class)->getVehicleAction($vehicle);
        }

        if ($this->hasKeyloopValuation()) {
            return App::make(SilverBullet::class)->getVehicleAction($vehicle, 'reserve');
        }

        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-reserve');
    }

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

    private function codeWeaversWidget(Vehicle $vehicle): array
    {
        return [
            'type' => 'component',
                'value' => 'CatalogCodeWeaversDeal',
            'data' => [
                'action' => 'reserve',
                'url' => 'https://services.codeweavers.net/navigator/redirectToApplication/reserve',
                'api_key' => Settings::get('finance-codeweavers-api_key'),
                'quote_id' => str_replace(
                    ['https://services.codeweavers.net/forms/quote/', '/apply'],
                    '',
                    $vehicle->defaultFinanceExample?->apply_url
                ),
                'title' => Settings::get('sales-codeweavers-reserve-button-text'),
                '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),
            ],
        ];
        // https://services.codeweavers.net/navigator/redirectToApplication/reserve?apiKey=d0EBQExY2Cr1v24kQx&quoteReference=d1c53d29-3029-44f3-8488-428aed24c323&organisationIdentifier=34999&organisationIdentifierType=CodeweaversReference
    }

    private function hasPaymentReservation(): bool
    {
        return Feature::isEnabled('reservations');
    }
}
