<?php

namespace App;

use App\Actions\IntegrationVerification\VerifyAutoTraderCoDriver;
use App\Actions\IntegrationVerification\VerifyAutoTraderPartEx;
use App\Actions\IntegrationVerification\VerifyAutoTraderSpecs;
use App\Actions\IntegrationVerification\VerifyBeepBeep;
use App\Actions\IntegrationVerification\VerifyCalltracks;
use App\Actions\IntegrationVerification\VerifyCampaignMonitor;
use App\Actions\IntegrationVerification\VerifyCapPartEx;
use App\Actions\IntegrationVerification\VerifyCapSpecs;
use App\Actions\IntegrationVerification\VerifyCodeWeavers;
use App\Actions\IntegrationVerification\VerifyDmsNavigator;
use App\Actions\IntegrationVerification\VerifyEnquiryMax;
use App\Actions\IntegrationVerification\VerifyEvolutionFunding;
use App\Actions\IntegrationVerification\VerifyHPILookup;
use App\Actions\IntegrationVerification\VerifyHPISpecs;
use App\Actions\IntegrationVerification\VerifyHPIValuation;
use App\Actions\IntegrationVerification\VerifyIvendi;
use App\Actions\IntegrationVerification\VerifyMailChimp;
use App\Actions\IntegrationVerification\VerifyMotorCheckSpecs;
use App\Actions\IntegrationVerification\VerifyMotordat;
use App\Actions\IntegrationVerification\VerifyPinewood;
use App\Actions\IntegrationVerification\VerifyRapidRtc;
use App\Actions\IntegrationVerification\VerifySilverBullet;
use App\Actions\IntegrationVerification\VerifySkupenet;
use App\Actions\IntegrationVerification\VerifySkoda;
use App\Facades\Settings;
use App\Modules\ImageSync\AutoImaging;
use App\Modules\ImageSync\AutoloadIt;
use App\Modules\ImageSync\Pyxel;
use App\Modules\Leasing\KeyloopFleetKompact;
use App\Modules\ImageSync\AutosOnShow;
use App\Modules\SalesChannels\AaCars;
use App\Modules\SalesChannels\Autoweb;
use App\Modules\SalesChannels\CarGuru;
use App\Modules\SalesChannels\CarsIreland;
use App\Modules\SalesChannels\CarSnip;
use App\Modules\SalesChannels\CarWow;
use App\Modules\SalesChannels\Carzone;
use App\Modules\SalesChannels\ChannelFeed;
use App\Modules\SalesChannels\EasiChat;
use App\Modules\SalesChannels\HeyCar;
use App\Modules\SalesChannels\EbayMotors;
use App\Modules\SalesChannels\Inventory;
use App\Modules\SalesChannels\MotoNovo;
use App\Modules\SalesChannels\MotorsCoUk;
use App\Modules\SalesChannels\OutAndAbout;
use App\Modules\SalesChannels\Phyron;
use App\Modules\Stock\AutoGrab;
use App\Modules\Stock\AutoTraderStock;
use App\Modules\Stock\CustomEndpoint;
use App\Modules\Stock\DealerInternet;
use App\Modules\Stock\DMSNavigator;
use App\Modules\Stock\ImportMap;
use App\Modules\Stock\KeyloopRev8;
use App\Modules\Stock\Modix;
use App\Modules\Stock\Motordat;
use App\Modules\Stock\Motors;
use App\Modules\Stock\Pinewood;
use App\Modules\Stock\Skupenet;
use App\Modules\Stock\Skoda;
use App\Services\AutoTrader;
use App\Services\OpenAI;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Services\KeyloopReservationHelper;
use Mtc\MercuryDataModels\Setting;
use Mtc\MercuryDataModels\Tenant;

class IntegrationRepository
{
    protected static array $concurrentEnabledCountLimit = [
        'sales-channels' => [
            'lite' => 2,
            'standard' => 5,
            'pro' => 999,
            'enterprise' => 999,
        ],
        'ai-content' => [
            'lite' => 1,
            'standard' => 1,
            'pro' => 1,
            'enterprise' => 1,
        ],
        'smart-image-management' => [
            'lite' => 1,
            'standard' => 1,
            'pro' => 1,
            'enterprise' => 1,
        ],
        'valuation' => [
            'lite' => 1,
            'standard' => 1,
            'pro' => 1,
            'enterprise' => 1,
        ],
        'lookup' => [
            'lite' => 1,
            'standard' => 1,
            'pro' => 1,
            'enterprise' => 1,
        ],
        'vehicle-specs' => [
            'lite' => 1,
            'standard' => 1,
            'pro' => 1,
            'enterprise' => 1,
        ],
    ];

    protected static array $vehicle_automation_types = [
        'vehicle-specs',
        'ai-content',
    ];

    protected static array $integrations = [
        'tiktok' => [
            'type' => 'socials',
            'config_key' => 'app-socials-tiktok',
        ],
        'facebook' => [
            'type' => 'socials',
            'config_key' => 'app-socials-facebook',
        ],
        'twitter' => [
            'type' => 'socials',
            'config_key' => 'app-socials-twitter',
        ],
        'youtube' => [
            'type' => 'socials',
            'config_key' => 'app-socials-youtube',
        ],
        'instagram' => [
            'type' => 'socials',
            'config_key' => 'app-socials-instagram',
        ],
        'linkedin' => [
            'type' => 'socials',
            'config_key' => 'app-socials-linkedin',
        ],
        'silver-bullet' => [
            'type' => 'sales',
            'config_key' => 'sales-silver-bullet-enabled',
            'verify_key' => 'sales-silver-bullet-verify',
            'verification' => VerifySilverBullet::class,
            'link' => '/settings/automotive/sales',
            'image' => [
                'src' => 'keyloop-ecommerce.svg',
                'alt' => 'Keyloop ecommerce',
            ],
        ],
        'stripe' => [
            'type' => 'sales',
            'config_key' => 'sales-stripe-enabled',
            'link' => '/settings/automotive/sales',
            'image' => [
                'src' => 'stripe-logo.png',
                'alt' => 'Payments with Stripe',
            ],
        ],
        'ivendi' => [
            'type' => 'finance',
            'config_key' => 'finance-ivendi-enabled',
            'verify_key' => 'finance-ivendi-verify',
            'verification' => VerifyIvendi::class,
            'link' => '/settings/automotive/finance',
            'image' => [
                'src' => 'ivendi.png',
                'alt' => 'iVendi',
            ],
        ],
        'code-weavers' => [
            'type' => 'finance',
            'config_key' => 'finance-codeweavers-enabled',
            'verify_key' => 'finance-codeweavers-verify',
            'verification' => VerifyCodeWeavers::class,
            'link' => '/settings/automotive/finance',
            'image' => [
                'src' => 'codeweavers.png',
                'alt' => 'CodeWeavers',
            ],
        ],
        'santander' => [
            'type' => 'finance',
            'config_key' => 'finance-santander-enabled',
            'link' => '/settings/automotive/finance',
            'image' => [
                'src' => 'santander.png',
                'alt' => 'Santander',
            ],
        ],
        'evolution-funding' => [
            'type' => 'finance',
            'config_key' => 'finance-evolution-enabled',
            'verify_key' => 'finance-evolution-verify',
            'verification' => VerifyEvolutionFunding::class,
            'link' => '/settings/automotive/finance',
            'image' => [
                'src' => 'evolution-funding.png',
                'alt' => 'Evolution Funding',
            ],
        ],
        'santander' => [
            'type' => 'finance',
            'config_key' => 'finance-santander-enabled',
            'link' => '/settings/automotive/finance',
            'image' => [
                'src' => 'santander.png',
                'alt' => 'Santander Consumer Finance',
            ],
        ],
        'enquiry-max' => [
            'type' => 'crm',
            'config_key' => 'crm-enquiry-max-enabled',
            'verify_key' => 'crm-enquiry-max-verify',
            'verification' => VerifyEnquiryMax::class,
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'enquiry-max.svg',
                'alt' => 'EnquiryMax',
            ],
        ],
        'salesforce' => [
            'type' => 'crm',
            'config_key' => 'salesforce-crm-enabled',
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'salesforce.webp',
                'alt' => 'Salesforce',
            ],
        ],
        'fuse' => [
            'type' => 'crm',
            'config_key' => 'fuse-crm-enabled',
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'fuse.png',
                'alt' => 'Fuse',
            ],
        ],
        'pinewood-crm' => [
            'type' => 'crm',
            'config_key' => 'pinewood-crm-enabled',
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'pinewood.png',
                'alt' => 'Pinewood CRM',
            ],
        ],
        'storm-ms-dynamics' => [
            'type' => 'crm',
            'config_key' => 'storm-ms-dynamics-crm-enabled',
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'ms-dynamics.jpeg',
                'alt' => 'MS Dynamics via Storm',
            ],
        ],
        'calltracks' => [
            'type' => 'crm',
            'config_key' => 'crm-calltracks-enabled',
            'verify_key' => 'crm-calltracks-verify',
            'verification' => VerifyCalltracks::class,
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'calltracks.png',
                'alt' => 'Calltracks',
            ],
        ],
        'rapid-rtc' => [
            'type' => 'crm',
            'config_key' => 'crm-rapid-rtc-enabled',
            'verify_key' => 'crm-rapid-rtc-verify',
            'verification' => VerifyRapidRtc::class,
            'link' => '/settings/crm/integrations',
            'image' => [
                'src' => 'keyloop-leads.svg',
                'alt' => 'Keyloop Leads',
            ],
        ],
        'webleads' => [
            'type' => 'crm',
            'config_key' => 'crm-webleads-enabled',
            'link' => '/settings/crm/integrations',
            'image' => [
                // WebLeads API uses a Keyloop URL
                'src' => 'keyloop-leads.svg',
                'alt' => 'WebLeads',
            ],
        ],
        'mail-chimp' => [
            'type' => 'newsletters',
            'config_key' => 'newsletters-mailchimp-enabled',
            'verify_key' => 'newsletters-mailchimp-verify',
            'verification' => VerifyMailChimp::class,
            'link' => '/settings/crm/newsletter',
            'image' => [
                'src' => 'mailchimp.png',
                'alt' => 'MailChimp',
            ],
        ],
        'campaign-monitor' => [
            'type' => 'newsletters',
            'config_key' => 'newsletters-campaign-monitor-enabled',
            'verify_key' => 'newsletters-campaign-monitor-verify',
            'verification' => VerifyCampaignMonitor::class,
            'link' => '/settings/crm/newsletter',
            'image' => [
                'src' => 'campaign-monitor.png',
                'alt' => 'Campaign Monitor',
            ],
        ],
        'cap' => [
            'type' => 'vehicle-specs',
            'config_key' => 'vehicle-spec-providers-cap-enabled',
            'verify_key' => 'vehicle-spec-providers-cap-verify',
            'verification' => VerifyCapSpecs::class,
            'link' => '/settings/automotive/specification-feature-synchronization',
            'image' => [
                'src' => 'cap.png',
                'alt' => ' CAP Data',
            ],
        ],
        'hpi' => [
            'type' => 'vehicle-specs',
            'config_key' => 'vehicle-spec-providers-hpi-enabled',
            'verify_key' => 'vehicle-spec-providers-hpi-verify',
            'verification' => VerifyHPISpecs::class,
            'link' => '/settings/automotive/specification-feature-synchronization',
            'image' => [
                'src' => 'hpi.svg',
                'alt' => ' HPI Data',
            ],
        ],
        'autotrader' => [
            'type' => 'vehicle-specs',
            'config_key' => 'vehicle-spec-providers-autotrader-enabled',
            'verify_key' => 'vehicle-spec-providers-autotrader-verify',
            'verification' => VerifyAutoTraderSpecs::class,
            'link' => '/settings/automotive/specification-feature-synchronization',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => ' AutoTrader specs',
            ],
        ],
        'motor-check' => [
            'type' => 'vehicle-specs',
            'config_key' => 'vehicle-spec-providers-motor-check-enabled',
            'verify_key' => 'vehicle-spec-providers-motor-check-verify',
            'verification' => VerifyMotorCheckSpecs::class,
            'link' => '/settings/automotive/specification-feature-synchronization',
            'image' => [
                'src' => 'motor-check.png',
                'alt' => 'MotorCheck specs',
            ],
        ],
        'autos-on-show' => [
            'type' => 'image-sync',
            'config_key' => 'image-sync-autos-on-show-enabled',
            'class' => AutosOnShow::class,
            'link' => '/settings/automotive/image-synchronization',
            'image' => [
                'src' => 'autos-on-show.png',
                'alt' => 'Autos On Show',
            ],
        ],
        'pyxel' => [
            'type' => 'image-sync',
            'config_key' => 'image-sync-pyxel-enabled',
            'class' => Pyxel::class,
            'link' => '/settings/automotive/image-synchronization',
            'image' => [
                'src' => 'pyxel.png',
                'alt' => 'Pyxel',
            ],
        ],
        'auto-imaging' => [
            'type' => 'image-sync',
            'config_key' => 'image-sync-auto-imaging-enabled',
            'class' => AutoImaging::class,
            'link' => '/settings/automotive/image-synchronization',
            'image' => [
                'src' => 'auto-imaging.png',
                'alt' => 'AutoImaging',
            ],
        ],
        'autoload-it' => [
            'type' => 'image-sync',
            'config_key' => 'image-sync-autoloadit-enabled',
            'link' => '/settings/automotive/image-synchronization',
            'class' => AutoloadIt::class,
            'image' => [
                'src' => 'autoloadit.png',
                'alt' => 'Autoload It',
            ],
        ],

        'fuzey' => [
            'type' => 'chat',
            'config_key' => 'chat-fuzey-enabled',
            'link' => '/settings/crm/live-chat',
            'widget' => 'Fuzey',
            'image' => [
                'src' => 'fuzey.webp',
                'alt' => 'Fuzey',
            ],
        ],
        'easichat' => [
            'type' => 'chat',
            'config_key' => 'easi-chat-enabled',
            'link' => '/settings/crm/live-chat',
            'widget' => 'EasiChat',
            'data' => [
                'key' => 'easi-chat-client_id',
            ],
            'image' => [
                'src' => 'easichat.png',
                'alt' => 'EasiChat',
            ],
        ],
        'visitor' => [
            'type' => 'chat',
            'config_key' => 'chat-visitor-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'visitorchat.png',
                'alt' => 'VisitorChat',
            ],
        ],
        'zendesk' => [
            'type' => 'chat',
            'config_key' => 'chat-zendesk-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'zendesk.png',
                'alt' => 'ZenDesk',
            ],
        ],
        'rapid-rtc-chat' => [
            'type' => 'chat',
            'config_key' => 'chat-rapid-rtc-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'keyloop-leads.svg',
                'alt' => 'Keyloop Leads Live Chat',
            ],
        ],
        'gubagoo' => [
            'type' => 'chat',
            'config_key' => 'chat-gubagoo-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'gubagoo.jpg',
                'alt' => 'Gubagoo',
            ],
        ],
        'live-chat' => [
            'type' => 'chat',
            'config_key' => 'chat-live-chat-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'live-chat.png',
                'alt' => ' Live Chat',
            ],
        ],
        'activ-engage' => [
            'type' => 'chat',
            'config_key' => 'chat-activ-engage-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'activengage.svg',
                'alt' => 'ActivEngage',
            ],
        ],
        'seezar' => [
            'type' => 'chat',
            'config_key' => 'chat-seezar-enabled',
            'link' => '/settings/crm/live-chat',
            'image' => [
                'src' => 'seezar.png',
                'alt' => 'Seezar AI',
            ],
        ],
        'car-gurus' => [
            'type' => 'sales-channels',
            'class' => CarGuru::class,
            'config_key' => 'sales-channels-car-gurus-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'car-gurus.svg',
                'alt' => ' Car Gurus Feed',
            ],
        ],
        'channel-feed' => [
            'type' => 'sales-channels',
            'class' => ChannelFeed::class,
            'config_key' => 'sales-channels-channel-feed-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'channable.png',
                'alt' => ' Channable Feed',
            ],
        ],
        'car-wow' => [
            'type' => 'sales-channels',
            'class' => CarWow::class,
            'config_key' => 'sales-channels-car-wow-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'car-wow.png',
                'alt' => ' Car Wow Feed',
            ],
        ],
        'car-snip' => [
            'type' => 'sales-channels',
            'class' => CarSnip::class,
            'config_key' => 'sales-channels-car-snip-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'car-snip.png',
                'alt' => ' Car Snip Feed',
            ],
        ],
        'aa-cars' => [
            'type' => 'sales-channels',
            'class' => AaCars::class,
            'config_key' => 'sales-channels-aa-cars-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'aa-cars.png',
                'alt' => 'Aa Cars Feed',
            ],
        ],
        'autoweb' => [
            'type' => 'sales-channels',
            'class' => Autoweb::class,
            'config_key' => 'sales-channels-autoweb-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'autoweb.svg',
                'alt' => 'Autoweb Feed',
            ],
        ],
        'inventory' => [
            'type' => 'sales-channels',
            'class' => Inventory::class,
            'config_key' => 'sales-channels-inventory-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'inventory.png',
                'alt' => 'Inventory Feed',
            ],
        ],
        'carzone' => [
            'type' => 'sales-channels',
            'class' => Carzone::class,
            'config_key' => 'sales-channels-carzone-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'carzone.jpg',
                'alt' => 'Carzone Feed',
            ],
        ],
        'cars-ireland' => [
            'type' => 'sales-channels',
            'class' => CarsIreland::class,
            'config_key' => 'sales-channels-cars-ireland-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'carsireland.png',
                'alt' => 'Cars Ireland Feed',
            ],
        ],
        'phyron-sync' => [
            'type' => 'image-sync',
            'class' => \App\Modules\ImageSync\Phyron::class,
            'config_key' => 'image-sync-phyron-enabled',
            'link' => '/settings/automotive/image-synchronization',
            'image' => [
                'src' => 'phyron.png',
                'alt' => 'Phyron Feed',
            ],
        ],
        'phyron' => [
            'type' => 'sales-channels',
            'class' => Phyron::class,
            'config_key' => 'sales-channels-phyron-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'phyron.png',
                'alt' => 'Phyron Feed',
            ],
        ],
        'hey-car' => [
            'type' => 'sales-channels',
            'class' => HeyCar::class,
            'config_key' => 'sales-channels-hey-car-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'hey-car.png',
                'alt' => ' Hey Car Feed',
            ],
        ],
        'out-and-about' => [
            'type' => 'sales-channels',
            'class' => OutAndAbout::class,
            'config_key' => 'sales-channels-out-and-about-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'out-and-about.svg',
                'alt' => 'Out and About Feed',
            ],
        ],
        'ebay-motors' => [
            'type' => 'sales-channels',
            'global' => true,
            'class' => EbayMotors::class,
            'config_key' => 'sales-channels-ebay-motors-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'ebay-motors.png',
                'alt' => 'Ebay Motors Feed',
            ],
        ],
        'motors-co-uk' => [
            'type' => 'sales-channels',
            'class' => MotorsCoUk::class,
            'config_key' => 'sales-channels-motors-co-uk-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'motors-co-uk.png',
                'alt' => 'Motors.co.uk Feed',
            ],
        ],
        'moto-novo' => [
            'type' => 'sales-channels',
            'class' => MotoNovo::class,
            'config_key' => 'sales-channels-moto-novo-enabled',
            'link' => '/settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'moto-novo.png',
                'alt' => 'MotoNovo Feed',
            ],
        ],
        'auto-trader-sales' => [
            'type' => 'sales-channels',
            'class' => AutoTraderStock::class,
            'config_key' => 'sales-channels-auto-trader-enabled',
            'link' => '/settings/automotive/autotrader',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => 'AutoTrader (sales channel)',
            ],
        ],
        'pinewood' => [
            'type' => 'stock',
            'class' => Pinewood::class,
            'config_key' => 'stock-pinewood-enabled',
            'verify_key' => 'stock-pinewood-verify',
            'verification' => VerifyPinewood::class,
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'pinewood.png',
                'alt' => 'Pinnacle Pinewood',
            ],
        ],
        'motordat' => [
            'type' => 'stock',
            'class' => Motordat::class,
            'config_key' => 'stock-motordat-enabled',
            'verify_key' => 'stock-motordat-verify',
            'verification' => VerifyMotordat::class,
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'motordat.webp',
                'alt' => 'Motordat',
            ],
        ],
        'keyloop-rev8' => [
            'type' => 'stock',
            'class' => KeyloopRev8::class,
            'config_key' => 'stock-keyloop-rev8-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'keyloop-rev8.svg',
                'alt' => 'Keyloop Rev8',
            ],
        ],
        'auto-trader' => [
            'type' => 'stock',
            'class' => AutoTraderStock::class,
            'config_key' => 'stock-auto-trader-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => 'AutoTrader (stock)',
            ],
        ],
        'modix' => [
            'type' => 'stock',
            'class' => Modix::class,
            'config_key' => 'stock-modix-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'modix.png',
                'alt' => 'Modix',
            ],
        ],
        'dms-navigator' => [
            'type' => 'stock',
            'class' => DMSNavigator::class,
            'config_key' => 'stock-dms-navigator-enabled',
            'verify_key' => 'stock-dms-navigator-verify',
            'verification' => VerifyDmsNavigator::class,
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'navigator.svg',
                'alt' => 'DMS Navigator',
            ],
        ],
        'skupenet' => [
            'type' => 'stock',
            'class' => Skupenet::class,
            'config_key' => 'stock-skupenet-enabled',
            'verify_key' => 'stock-skupenet-verify',
            'verification' => VerifySkupenet::class,
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'skupenet.png',
                'alt' => 'Skupenet',
            ],
        ],
        'dealer-internet' => [
            'type' => 'offer-stock',
            'class' => DealerInternet::class,
            'config_key' => 'stock-dealer-internet-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
        ],
        'skoda' => [
            'type' => 'offer-stock',
            'class' => Skoda::class,
            'config_key' => 'stock-skoda-enabled',
            'verify_key' => 'stock-skoda-verify',
            'verification' => VerifySkoda::class,
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'skoda.svg',
                'alt' => 'Skoda',
            ],
        ],
        'custom-feed' => [
            'type' => 'stock',
            'class' => CustomEndpoint::class,
            'config_key' => 'stock-endpoint-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'custom-feed.png',
                'alt' => 'Custom Stock Feed',
            ],
        ],
        'import-map' => [
            'type' => 'stock',
            'class' => ImportMap::class,
            'config_key' => 'stock-file-enabled',
            'link' => '/settings/import-maps',
            'image' => [
                'src' => 'import-map.png',
                'alt' => 'File on FTP server, mapped via import map',
            ],
        ],
        'motors' => [
            'type' => 'stock',
            'class' => Motors::class,
            'config_key' => 'stock-motors-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'motors-co-uk.png',
                'alt' => 'Motors.co.uk Stock Feed',
            ],
        ],
        'autograb' => [
            'type' => 'stock',
            'class' => AutoGrab::class,
            'config_key' => 'stock-autograb-enabled',
            'link' => '/settings/automotive/dms-vehicle-sync',
            'image' => [
                'src' => 'autograb.png',
                'alt' => 'AutoGrab.co.uk Stock Notifications',
            ],
        ],
        'keyloop' => [
            'type' => 'stock-reservation',
            'config_key' => 'keyloop-reservations-enabled',
            'class' => KeyloopReservationHelper::class,
        ],
        'hpi-valuation' => [
            'type' => 'valuation',
            'config_key' => 'valuation-hpi-enabled',
            'verify_key' => 'valuation-hpi-verify',
            'verification' => VerifyHPIValuation::class,
            'link' => '/settings/automotive/valuation',
            'image' => [
                'src' => 'hpi.svg',
                'alt' => 'HPI Data',
            ],
        ],
        'cap-valuation' => [
            'type' => 'valuation',
            'config_key' => 'valuation-cap-enabled',
            'verify_key' => 'valuation-cap-verify',
            'verification' => VerifyCapPartEx::class,
            'link' => '/settings/automotive/valuation',
            'image' => [
                'src' => 'cap.png',
                'alt' => 'CAP Data',
            ],
        ],
        'bca-valuation' => [
            'type' => 'valuation',
            'config_key' => 'valuation-bca-enabled',
            'link' => '/settings/automotive/valuation',
            'image' => [
                'src' => 'bca_logo.png',
                'alt' => 'BCA',
            ],
        ],
        'motor-check-valuation' => [
            'type' => 'valuation',
            'config_key' => 'valuation-motor-check-enabled',
            'link' => '/settings/automotive/valuation',
            'image' => [
                'src' => 'motor-check.png',
                'alt' => 'MotorCheck',
            ],
        ],
        'auto-trader-valuation' => [
            'type' => 'valuation',
            'config_key' => 'valuation-auto-trader-enabled',
            'verify_key' => 'valuation-auto-trader-verify',
            'verification' => VerifyAutoTraderPartEx::class,
            'link' => '/settings/automotive/valuation',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => 'AutoTrader',
            ],
        ],
        'cap-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-cap-enabled',
            'verify_key' => 'lookup-cap-verify',
            'verification' => VerifyCapPartEx::class,
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'cap.png',
                'alt' => 'CAP Data',
            ],
        ],
        'auto-trader-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-auto-trader-enabled',
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => 'AutoTrader',
            ],
        ],
        'bca-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-bca-enabled',
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'bca_logo.png',
                'alt' => 'BCA',
            ],
        ],
        'eva-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-eva-enabled',
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'eva_logo.svg',
                'alt' => 'EVA',
            ],
        ],
        'motorcheck-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-motor-check-enabled',
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'motor-check.png',
                'alt' => 'MotorCheck',
            ],
        ],
        'beep-beep-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-beepbeep-enabled',
            'verify_key' => 'lookup-beep-beep-verify',
            'verification' => VerifyBeepBeep::class,
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'beepbeep.png',
                'alt' => 'BeepBeep Data',
            ],
        ],
        'hpi-lookup' => [
            'type' => 'lookup',
            'config_key' => 'lookup-hpi-enabled',
            'verify_key' => 'lookup-hpi-verify',
            'verification' => VerifyHPILookup::class,
            'link' => '/settings/automotive/lookup',
            'image' => [
                'src' => 'hpi.svg',
                'alt' => 'HPI Data',
            ],
        ],
        'open-ai' => [
            'type' => 'ai-content',
            'class' => OpenAI::class,
            'config_key' => 'open-ai-enabled',
            'link' => '/settings/automotive/ai',
            'image' => [
                'src' => 'open-ai.png',
                'alt' => 'OpenAI Content',
            ],
        ],
        'auto-trader-co-driver' => [
            'type' => 'ai-content',
            'class' => AutoTrader::class,
            'config_key' => 'ai-content-auto-trader-enabled',
            'verify_key' => 'ai-content-auto-trader-verify',
            'verification' => VerifyAutoTraderCoDriver::class,
            'link' => '/settings/automotive/ai',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => 'AutoTrader Co Driver',
            ],
        ],
        'occupop' => [
            'type' => 'job',
            'config_key' => 'jobs-occupop-enabled',
            'link' => '/settings/site/content',
            'image' => [
                'src' => 'occupop.webp',
                'alt' => 'Occupop',
            ],
        ],
        'auto-trader-smart-image-management' => [
            'type' => 'smart-image-management',
            'class' => AutoTrader::class,
            'config_key' => 'auto-trader-smart-image-management-enabled',
            'link' => '/settings/automotive/autotrader',
            'image' => [
                'src' => 'auto-trader.png',
                'alt' => 'AutoTrader Co Driver (smart image management)',
            ],
        ],
        'keyloop-fleet-kompact' => [
            'type' => 'lease-data',
            'link' => '/settings/automotive/leasing',
            'class' => KeyloopFleetKompact::class,
            'config_key' => 'leasing-keyloop-fleet-kompact-enabled',
            'image' => [
                'src' => 'keyloop-leasing.svg',
                'alt' => 'Keayloop Leasing',
            ],
        ],
        'easichat-stock' => [
            'type' => 'sales-channels',
            'class' => EasiChat::class,
            'config_key' => 'sales-channels-easichat-enabled',
            'link' => 'settings/automotive/sales-channels-feeds',
            'image' => [
                'src' => 'easichat.png',
                'alt' => 'EasiChat (stock enabled)',
            ],
        ],
    ];

    /**
     * Get list of enabled integrations
     *
     * @return array
     */
    public function getEnabled(): array
    {
        $enabled = $this->findEnabledIntegrations();
        return collect(self::$integrations)
            ->filter(fn($integration) => isset($enabled[$integration['config_key']]))
            ->map(function ($integration) {
                unset($integration['config_key']);
                if (isset($integration['image']['src'])) {
                    $integration['image']['src'] = config('app.url') . '/api/assets/' . $integration['image']['src'];
                }
                $integration['title'] = __('integrations.types.' . $integration['type']);
                return $integration;
            })
            ->values()
            ->toArray();
    }

    /**
     * Find all integrations for a specific type
     *
     * @param string $type
     * @return Collection
     */
    public function getAllForType(string $type, bool $checkEnabled = false): Collection
    {
        return collect(self::$integrations)
            ->filter(fn($integration) => $integration['type'] === $type)
            ->map(function ($integration) use ($checkEnabled) {
                if ($checkEnabled) {
                    $integration['active'] = Settings::get($integration['config_key']);
                }
                return $integration;
            });
    }

    /**
     * Find enabled integrations for a specific type
     *
     * @param string $type
     * @return \Illuminate\Support\Collection
     */
    public function getEnabledForType(string $type)
    {
        $enabled = $this->findEnabledIntegrations();
        return collect(self::$integrations)
            ->filter(fn($integration) => $integration['type'] === $type)
            ->filter(fn($integration) => isset($enabled[$integration['config_key']]));
    }

    public function isEnabled(string $name): bool
    {
        $enabled = $this->findEnabledIntegrations();
        $integration = self::$integrations[$name];
        return $integration && isset($enabled[$integration['config_key']]);
    }

    /**
     * Check if given config key is enable flag for an integration
     *
     * @param string $key
     * @return bool
     */
    public function keyIsEnableSettingValue(string $key): bool
    {
        return collect(self::$integrations)
            ->filter(fn($integration) => $integration['config_key'] === $key)
            ->isNotEmpty();
    }

    /**
     * Get integration type from enable key
     *
     * @param string $key
     * @return string|null
     */
    public function getTypeFromKey(string $key): ?string
    {
        return collect(self::$integrations)
            ->filter(fn($integration) => $integration['config_key'] === $key)
            ->first()['type'] ?? null;
    }

    /**
     * Get limit of concurrent integrations for type based on tier
     *
     * @param string $type
     * @param string $tier
     * @return int
     */
    public function getLimitForType(string $type, string $tier): int
    {
        if (array_key_exists($type, self::$concurrentEnabledCountLimit)) {
            return self::$concurrentEnabledCountLimit[$type][$tier];
        }

        return $tier === Tier::ENTERPRISE->value ? 99 : 1;
    }

    /**
     * Check how many integrations of type are enabled in input
     *
     * @param array $input
     * @param string $type
     * @return int
     */
    public function checkEnabledCountForType(array $input, string $type): int
    {
        $type_enable_flags = collect(self::$integrations)
            ->filter(fn($integration) => $integration['type'] === $type)
            ->pluck('config_key');

        return collect($input)
            ->filter(fn($value, $key) => $type_enable_flags->search($key) !== false && $value)
            ->count();
    }

    public function verifyIntegration(string $verifyKey): bool|Response
    {
        $toCheck = collect(self::$integrations)
            ->filter(fn($integration) => $verifyKey === ($integration['verify_key'] ?? null))
            ->first();

        if ($toCheck && !empty($toCheck['verification'])) {
            return App::make($toCheck['verification'])->verify();
        }

        return false;
    }

    public function enabledByType(Tenant $tenant): Collection
    {
        tenancy()->initialize($tenant);
        $integrations = collect($this->getEnabled())
            ->map(fn($integration, $key) => [
                'name' => $integration['image']['alt'] ?? $key,
                'type' => $integration['type'],
                'frequency' => $integration['type'] === 'stock'
                    ? Settings::get('stock-sync-frequency')
                    : null,
            ])
            ->groupBy(fn($integration) => $integration['type']);
        tenancy()->end();
        return $integrations;
    }

    /**
     * Find entries of type that have set values
     *
     * @param string $type
     * @return Collection
     */
    public function findNonEmptyValuesForType(string $type)
    {
        return $this->getAllForType($type, true)
            ->filter(fn($integration) => !empty($integration['active']))
            ->map(fn($integration) => $integration['active']);
    }

    public function getAutomationsForVehicle(): array
    {
        return collect(self::$vehicle_automation_types)
            ->keyBy(fn($type) => $type)
            ->map(fn($type) => $this->getEnabledForType($type))
            ->filter()
            ->map(fn($enabled, $type) => $enabled->map(fn($entry, $key) => [
                'name' => __("integrations.automations.$type", ['provider' => __("integrations.names.$key")]),
                'value' => $type,
            ]))
            ->flatten(1)
            ->toArray();
    }

    /**
     * Find enabled integrations from settings
     *
     * @return Collection
     */
    protected function findEnabledIntegrations(): Collection
    {
        return Setting::query()
            ->whereIn('config_key', collect(self::$integrations)->pluck('config_key'))
            ->where('value', 1)
            ->get()
            ->keyBy('config_key');
    }
}
