<?php

namespace App\Http\Resources;

use App\Facades\Feature;
use App\Facades\Settings;
use App\Modules\PlaceholderImages\ImaginStudio;
use App\Traits\RetrievesContent;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\KeyloopFleetKompactOptionType;
use Mtc\MercuryDataModels\KeyloopLeaseOptionPrice;
use Mtc\MercuryDataModels\Leasing\KeyloopLeaseFinanceService;

class LeaseVehicleResource extends JsonResource
{
    use RetrievesContent;

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $this->resource->load([
            'options.price',
            'spec.category',
        ]);

        $this->resource->fuel_type = $this->resource->fuelType?->name;
        $this->resource->transmission = $this->resource->transmission?->name;
        $this->resource->body_style = $this->resource->bodyStyle?->name;

        if (Settings::get('lease-vehicle-labels-enabled')) {
            $this->resource->load([
                'labels'
            ]);
        }

        $resource = $this->resource->only([
            'slug',
            'external_variant_id',
            'name',
            'derivative',
            'make',
            'model',
            'transmission',
            'bodyStyle',
            'fuelType',
            'type',
            'engine_size_cc',
            'brake_horsepower',
            'co2',
            'door_count',
            'seats',
            'road_fund_licence',
            'price_ex_vat_ex_vrt',
            'price_inc_vat_ex_vrt',
            'vehicle_vrt',
            'price_inc_vat_inc_vrt',
            'delivery_ex_vat_ex_vrt',
            'delivery_inc_vat_ex_vrt',
            'delivery_vrt',
            'delivery_inc_vat_inc_vrt',
        ]);

        $resource['imagin_studio_base_url'] = Feature::isEnabled('imagin-studio-placeholders')
            ? (new ImaginStudio())->getBaseUrl()
            : null;

        $finance_service = new KeyloopLeaseFinanceService();
        $resource['spec'] = $this->specforDisplay();
        $resource['options'] = $this->optionsforDisplay();
        $resource['colours'] = $this->coloursForDisplay();
        $resource['trims'] = $this->trimsForDisplay();
        $resource['finance_options'] = $finance_service->getVariantFinance($this->resource);
        $resource['road_tax_monthly'] = round($this->resource->road_fund_licence / 12, 2);
        $resource['finance_settings'] = [
            'contract_terms' => config('leasing.keyloop.contract_terms'),
            'deposit_quantity_months' => config('leasing.keyloop.deposit_quantity_months'),
            'annual_mileages' => config('leasing.keyloop.annual_mileages'),
        ];
        $resource['labels'] = Settings::get('lease-vehicle-labels-enabled')
            ? $this->resource->labels->whereIn('type', ['', 'all', 'fpa'])->values()
            : [];
        $resource['rrp'] = $this->getRrp();
        $resource['seo'] = $this->fillSeo('lease-vehicle');

        return $resource;
    }

    protected function getRrp()
    {
        return $this->resource->price_inc_vat_inc_vrt;
    }

    protected function specforDisplay()
    {
        $spec = [];

        $this->resource->spec->each(function ($item) use (&$spec) {
            $category = $item->category?->name ?? 'Miscellaneous';

            if (!array_key_exists($category, $spec)) {
                $spec[$category] = [];
            }

            $spec[$category][] = $item->name;
            asort($spec[$category]);
        });

        ksort($spec);
        return $spec;
    }

    protected function optionsForDisplay()
    {
        return $this->resource->options->map(function ($item) {

            $option_type = match (strtoupper($item->option_type)) {
                'P' => KeyloopFleetKompactOptionType::PACK,
                default => KeyloopFleetKompactOptionType::FACTORY_OPTION,
            };

            $price = $item->getPrice($this->resource->external_variant_id, $option_type) ?? null;

            return [
                'id' => $item->id,
                'name' => $item->name,
                'external_variant_id' => $item->name,
                'option_type' => $item->option_type,
                'option_code' => $item->option_code,
                'default_vat_code' => $item->default_vat_code,
                'price_option_code' => $price?->option_code,
                'price_ex_vat_ex_vrt' => $price?->price_ex_vat_ex_vrt ?? 0,
                'price_inc_vat_inc_vrt' => $price?->price_inc_vat_inc_vrt ?? 0,
                'vrt' => $price?->vrt ?? 0,
                'rrp' => $this->itemRrp($price),
            ];
        });
    }

    protected function itemRrp(?KeyloopLeaseOptionPrice $price): float
    {
        return round($price?->price_inc_vat_inc_vrt, 2);
    }

    protected function coloursForDisplay()
    {
        $colours = $this->resource->getColours()->map(function ($item) {
            $price = $item->getPrice($this->resource->external_variant_id, KeyloopFleetKompactOptionType::COLOUR);

            return [
                'id' => $item->id,
                'name' => $item->name,
                'colour_code' => $item->colour_code,
                'generic_colour_code' => $item->generic_colour_code,
                'generic_colour_name' => $this->getGenericColourName($item->generic_colour_code),
                'hex_code' => $item->hex_code,
                'gradient_hex_code' => $item->gradient_hex_code,
                'price_option_code' => $price?->option_code,
                'price_ex_vat_ex_vrt' => $price?->price_ex_vat_ex_vrt ?? 0,
                'price_inc_vat_inc_vrt' => $price?->price_inc_vat_inc_vrt ?? 0,
                'vrt' => $price?->vrt ?? 0,
                'rrp' => $this->itemRrp($price),
            ];
        })->toArray();

        shuffle($colours);
        return $colours;
    }

    protected function trimsForDisplay()
    {
        return $this->resource->getTrims()->map(function ($item) {
            $price = $item->getPrice($this->resource->external_variant_id, KeyloopFleetKompactOptionType::TRIM);

            return [
                'id' => $item->id,
                'name' => $item->name,
                'external_variant_id' => $item->name,
                'option_type' => $item->option_type,
                'option_code' => $item->option_code,
                'default_vat_code' => $item->default_vat_code,
                'price_option_code' => $price?->option_code,
                'price_ex_vat_ex_vrt' => $price?->price_ex_vat_ex_vrt ?? 0,
                'price_inc_vat_inc_vrt' => $price?->price_inc_vat_inc_vrt ?? 0,
                'vrt' => $price?->vrt ?? 0,
                'rrp' => $this->itemRrp($price),
            ];
        });
    }

    private function getGenericColourName(string $code): string
    {
        return match ($code) {
            'BGE' => 'Beige',
            'BLK' => 'Black',
            'BLU' => 'Blue',
            'BRN' => 'Brown',
            'GLD' => 'Gold',
            'GRN' => 'Green',
            'GRY' => 'Grey',
            'ORN' => 'Orange',
            'RED' => 'Red',
            'S' => 'Silver',
            'SLV' => 'Silver',
            'WHT' => 'White',
            'YLW' => 'Yellow',
            default => 'Black',
        };
    }
}
