<?php

namespace App\Modules\VehicleLabels\Http\Resources;

use App\Facades\Labels;
use App\Facades\Settings;
use App\IntegrationRepository;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Colour;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Franchise;
use Mtc\MercuryDataModels\FuelType;
use Mtc\MercuryDataModels\TransmissionType;
use Mtc\MercuryDataModels\VehicleMake;
use App\Models\ImportMap;
use Mtc\MercuryDataModels\VehicleModel;

class LabelView extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $has_stock_provider = new IntegrationRepository()->getEnabledForType('stock')->isNotEmpty();
        $this->resource->couldAutomate = Settings::get('vehicle-labels-enabled') || $has_stock_provider;
        $this->resource->data = $this->getDataValues();
        $this->resource->vehicle_count = $this->resource->vehicles->count();
        return parent::toArray($request);
    }

    private function getDataValues()
    {
        $data = $this->resource->data ?? [];

        // key options by label_rules.condition_field
        $data['options'] = [];

        if (!isset($data['auto_assign'])) {
            $data['auto_assign'] = false;
            $data['assign_when'] = false;
        }

        if (!isset($data['auto_revoke'])) {
            $data['auto_revoke'] = false;
            $data['revoke_when'] = false;
        }

        // default vehicle applicabiltiy to true
        if (!isset($data['applies_to_stock_vehicles'])) {
            $data['applies_to_stock_vehicles'] = true;
        }

        // default lease vehicle applicabiltiy to true
        if (!isset($data['applies_to_lease_vehicles'])) {
            $data['applies_to_lease_vehicles'] = true;
        }

        $data['automation_options'] = Labels::getAutomationOptions();
        $data['display_type_options'] = [
            [
                'id' => 'all',
                'name' => 'All'
            ],
            [
                'id' => 'srp',
                'name' => 'Search Page Only'
            ],
            [
                'id' => 'fpa',
                'name' => 'Full Page Advert Only'
            ],
        ];

        $data['advanced_rules'] = false;

        $colours = Colour::query()
            ->whereNotNull('hex_code')
            ->get()
            ->map(fn(Colour $colour) => [
                'id' => $colour->hex_code,
                'name' => $colour->colour,
                'hex' => $colour->hex_code,
            ]);

        $data['options']['colours'] = collect([
            [
                'id' => 'default',
                'name' => 'Default label colour',
                'hex' => null,
            ],
            [
                'id' => Settings::get('app-primary-colour'),
                'name' => 'Site primary colour',
                'hex' => Settings::get('app-primary-colour'),
            ],
            [
                'id' => Settings::get('app-secondary-colour'),
                'name' => 'Site secondary colour',
                'hex' => Settings::get('app-secondary-colour'),
            ],
            [
                'id' => Settings::get('app-tertiary-colour'),
                'name' => 'Site tertiary colour',
                'hex' => Settings::get('app-tertiary-colour'),
            ],
            [
                'id' => Settings::get('app-layer-light-colour'),
                'name' => 'Site light colour',
                'hex' => Settings::get('app-layer-light-colour'),
            ],
            [
                'id' => Settings::get('app-layer-accent-colour'),
                'name' => 'Site accent colour',
                'hex' => Settings::get('app-layer-accent-colour'),
            ],
        ])
            ->merge($colours);

        $data['options']['text_colours'] = [
            [
                'name' => 'Dark',
                'id' => Settings::get('app-text-colour')

            ],
            [
                'name' => 'Light',
                'id' => Settings::get('app-layer-light-colour')
            ],
        ];

        if (Settings::get('vehicle-labels-advanced-rules-enabled')) {
            $data['advanced_rules'] = true;
            $data['rules'] = $this->populateAdvancedRules($this->getAdvancedRules(), $this->resource->rules);
            $data['options']['vehicle_is_new'] = [
                [
                    'id' => '0',
                    'name' => 'false'
                ],
                [
                    'id' => '1',
                    'name' => 'true'
                ]
            ];
            $data['options']['vehicle_is_used'] = [
                [
                    'id' => '0',
                    'name' => 'false'
                ],
                [
                    'id' => '1',
                    'name' => 'true'
                ]
            ];
            $data['options']['vehicle_is_demo'] = [
                [
                    'id' => '0',
                    'name' => 'false'
                ],
                [
                    'id' => '1',
                    'name' => 'true'
                ]
            ];
            $data['options']['is_vat_qualifying'] = [
                [
                    'id' => '0',
                    'name' => 'false'
                ],
                [
                    'id' => '1',
                    'name' => 'true'
                ]
            ];
            $data['options']['vrm_is_empty'] = [
                [
                    'id' => '0',
                    'name' => 'false'
                ],
                [
                    'id' => '1',
                    'name' => 'true'
                ]
            ];
            $data['options']['vehicle_type'] = Labels::getVehicleTypeOptions();
            $data['options']['transmission_id'] = TransmissionType::orderBy('name')
                ->get()
                ->map(fn($option) => [
                    'id' => (string) $option->id,
                    'name' => $option->name
                ])->toArray();
            $data['options']['fuel_type_id'] = FuelType::orderBy('name')
                ->get()
                ->map(fn($option) => [
                    'id' => (string) $option->id,
                    'name' => $option->name
                ])->toArray();

            $data['options']['make_ids'] = VehicleMake::orderBy('name')
                ->get()
                ->map(fn($option) => [
                    'id' => (string) $option->id,
                    'name' => $option->name
                ])->toArray();
            $data['options']['model_ids'] = VehicleModel::orderBy('name')
                ->get()
                ->map(fn($option) => [
                    'id' => (string) $option->id,
                    'make_id' => (string) $option->make_id,
                    'name' => $option->name
                ])->toArray();
            $data['options']['dealership_ids'] = Dealership::query()
                ->where('active', '=', true)
                ->orderBy('name')
                ->get()
                ->map(fn($option) => [
                    'id' => (string) $option->id,
                    'name' => $option->name
                ])->toArray();

            $data['options']['stock_providers'] = ImportMap::query()
                ->where('type', 'vehicle')
                ->whereHas('fields')
                ->select(['id', 'name'])
                ->get()
                ->map(fn(ImportMap $map) => [
                    'id' => 'import-map-' . $map->id,
                    'name' => $map->name,
                ])->toArray();

            $data['options']['franchise_ids'] = Franchise::query()
                ->orderBy('name')
                ->get()
                ->map(fn($option) => [
                    'id' => (int) $option->id,
                    'name' => $option->name
                ])->toArray();
        }

        return $data;
    }

    private function getAdvancedRules()
    {
        return [
            'transmission_id' => [
                'name' => 'Transmission Type',
                'value_data_type' => 'id',
                'condition_value' => null,
            ],
            'fuel_type_id' => [
                'name' => 'Fuel Type',
                'value_data_type' => 'id',
                'condition_value' => null,
            ],
            'vehicle_age_min' => [
                'name' => 'Vehicle Age Min (years compared to now)',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_age_max' => [
                'name' => 'Vehicle Age Max (years compared to now)',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'manufacture_year_min' => [
                'name' => 'Manufacture Year Min',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'manufacture_year_max' => [
                'name' => 'Manufacture Year Max',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_mileage_min' => [
                'name' => 'Vehicle Mileage Min',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_mileage_max' => [
                'name' => 'Vehicle Mileage Max',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_days_in_stock_min' => [
                'name' => 'Days In Stock Min',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_days_in_stock_max' => [
                'name' => 'Days In Stock Max',
                'value_data_type' => 'integer',
                'condition_value' => null,
            ],
            'vehicle_type' => [
                'name' => 'Vehicle Type',
                'value_data_type' => 'string',
                'condition_value' => null,
            ],
            'vehicle_category' => [
                'name' => 'Vehicle Category',
                'value_data_type' => 'string',
                'condition_value' => null,
            ],
            'vehicle_is_new' => [
                'name' => 'Vehicle Is New',
                'value_data_type' => 'boolean',
                'condition_value' => null,
            ],
            'vehicle_is_used' => [
                'name' => 'Vehicle Is Used',
                'value_data_type' => 'boolean',
                'condition_value' => null,
            ],
            'vehicle_is_demo' => [
                'name' => 'Vehicle Is Demo',
                'value_data_type' => 'boolean',
                'condition_value' => null,
            ],
            'vehicle_price_min' => [
                'name' => 'Vehicle Price Min',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vehicle_price_max' => [
                'name' => 'Vehicle Price Max',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vehicle_mpg_min' => [
                'name' => 'MPG Min',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'vehicle_mpg_max' => [
                'name' => 'MPG Max',
                'value_data_type' => 'decimal',
                'condition_value' => null,
            ],
            'is_vat_qualifying' => [
                'name' => 'VAT Qualifying',
                'value_data_type' => 'boolean',
                'condition_value' => null,
            ],
            'vrm_is_empty' => [
                'name' => 'VRM is empty',
                'value_data_type' => 'boolean',
                'condition_value' => null,
            ],
            'vrms_included' => [
                'name' => 'VRMs included',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'vrms_excluded' => [
                'name' => 'VRMs Excluded',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'make_ids' => [
                'name' => 'Makes',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'model_ids' => [
                'name' => 'Models',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'dealership_ids' => [
                'name' => 'Dealerships',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'stock_providers' => [
                'name' => 'Stock Providers',
                'value_data_type' => 'json',
                'condition_value' => null,
            ],
            'active_from' => [
                'name' => 'Active From',
                'value_data_type' => 'date',
                'condition_value' => null,
            ],
            'active_to' => [
                'name' => 'Active To',
                'value_data_type' => 'date',
                'condition_value' => null,
            ],
        ];
    }

    /**
     * set the values of any advanced rules which exist in the label's rules
     *
     * @param array $advanced_rules
     * @param array $label_rules
     * @return array|mixed
     */
    private function populateAdvancedRules($advanced_rules = [], $label_rules = [])
    {
        $label_rules->each(function ($rule) use (&$advanced_rules) {
            $advanced_rules[$rule->condition_field]['condition_value'] = $rule->getValue();
        });

        return $advanced_rules;
    }
}
