<?php

namespace App\ExportMaps;

use App\ExportMaps\Contracts\ExportMapType;
use App\IntegrationRepository;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Dealership;

class DealershipExportMap implements ExportMapType
{
    public const NON_QUERYABLE_FIELDS = [
        'custom1',
        'custom2',
        'custom3',
        'custom4',
        'custom5',
        'custom6',
        'empty',
    ];

    public function name(): string
    {
        return 'Dealerships';
    }

    public function columns(bool $onlyEnabledIntegrations = false): array
    {
        return array_merge(
            $this->getDefaultDataFields(),
            $this->getIntegrationDealershipDataFields($onlyEnabledIntegrations),
        );
    }

    public function queryableColumns(bool $onlyEnabledIntegrations = false): array
    {
        return array_filter(
            array_diff_key(
                $this->columns($onlyEnabledIntegrations),
                array_flip(self::NON_QUERYABLE_FIELDS)
            ),
            fn ($value, $key) => !str_starts_with($key, 'data.'),
            ARRAY_FILTER_USE_BOTH
        );
    }

    public function query(): Builder
    {
        return Dealership::query();
    }

    private function getDefaultDataFields(): array
    {
        return [
            'id' => 'Dealership ID',
            'name' => 'Name',
            'slug' => 'Slug',
            'email' => 'Email',
            'contact_no' => 'Phone',
            'active' => 'Is Active',
            'address1' => 'Address 1',
            'address2' => 'Address 2',
            'city' => 'City',
            'county' => 'County',
            'postcode' => 'Postcode',
            'country' => 'Country',
            'lat' => 'Latitude',
            'lng' => 'Longitude',
            'timezone' => 'Timezone',
            'franchise_id' => 'Franchise ID',
            'franchise.name' => 'Franchise Name',
            'external_showroom_url' => 'External Showroom URL',
            'notes' => 'Notes',
            'order' => 'Order',
            'created_at' => 'Created at',
            'updated_at' => 'Updated at',
            'empty' => 'Empty value',
            'custom1' => '[Custom] - Mapping Rules Field 1',
            'custom2' => '[Custom] - Mapping Rules Field 2',
            'custom3' => '[Custom] - Mapping Rules Field 3',
            'custom4' => '[Custom] - Mapping Rules Field 4',
            'custom5' => '[Custom] - Mapping Rules Field 5',
            'custom6' => '[Custom] - Mapping Rules Field 6',
        ];
    }

    private function getIntegrationDealershipDataFields(bool $onlyEnabledIntegrations): array
    {
        $integrationRepository = App::make(IntegrationRepository::class);
        $integrations = $onlyEnabledIntegrations
            ? $integrationRepository->getEnabledForType('sales-channels')
            : $integrationRepository->getAllForType('sales-channels');

        return $integrations
            ->filter(fn ($integration) => !empty($integration['class'])
                && class_exists($integration['class'])
                && method_exists($integration['class'], 'dealershipAdditionalDataFields'))
            ->flatMap(function ($integration) {
                $instance = App::make($integration['class']);
                $fields = $instance->dealershipAdditionalDataFields();
                return collect($fields)->mapWithKeys(fn ($fieldData, $fieldKey) => [
                    'data.' . $fieldKey => '[Dealership] ' . ($fieldData['label'] ?? $fieldKey),
                ]);
            })
            ->all();
    }
}
