<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Traits\HasPlaceholderImage;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Events\LoadVehicleDataFields;
use Mtc\MercuryDataModels\Traits\HasVehicleCustomAttributes;
use Mtc\MercuryDataModels\Jobs\TrackResourceView;
use Mtc\MercuryDataModels\Vehicle;

class VehiclesCompareResource extends JsonResource
{
    use HasPlaceholderImage;
    use HasVehicleCustomAttributes;

    private Collection $placeholder;

    /**
     * Transform the resource collection into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    #[\Override]
    public function toArray($request)
    {
        $this->trackViews();
        $this->resource = $this->resource
            ->map(fn($vehicle) => $this->mapVehicle($vehicle));

        return parent::toArray($request);
    }

    public function mapVehicle(Vehicle $vehicle)
    {
        $data = [
            'id' => $vehicle->id,
            'title' => $vehicle->title,
            'derivative' => $vehicle->derivative,
            'slug' => $vehicle->slug,
            'is_new' => $vehicle->is_new,
            'price' => $vehicle->price,
            'colour' => $vehicle->colour,
            'make' => Settings::get('automotive-vehicle-brand-on-filter-card')
                ? [
                    'name' => $vehicle->make->name ?? '',
                    'logo' => $vehicle->make->logo ?? '',
                    'slug' => $vehicle->make->slug ?? '',
                ]
                : null,
            'fuel_type' => $vehicle->fuelType?->name,
            'transmission' => $vehicle->transmission?->name,
            'bodystyle' => $vehicle->bodystyle?->name,
            'mpg' => $vehicle->mpg,
            'co2' => $vehicle->co2,
            'is_reserved' => $vehicle->is_reserved,
            'door_count' => $vehicle->door_count,
            'seats' => $vehicle->seats,
            'odometer_mi' => $vehicle->odometer_mi,
            'odometer_km' => $vehicle->odometer_km,
            'manufacture_year' => $vehicle->manufacture_year,
            'registration_number' => $vehicle->registration_number,
            'finance_example' => $this->getFinanceExample($vehicle),
            'model' => Settings::get('automotive-vehicle-model-on-filter-card')
                ? [
                    'name' => $vehicle->model->name ?? '',
                    'slug' => $vehicle->model->slug ?? '',
                ]
                : $vehicle->model?->name,
            'original_price' => $vehicle->original_price,
            'previous_price' => $vehicle->previous_price,
            'rrp_price' => $vehicle->rrp_price,
            'type' => $vehicle->type,
            'extra' => $this->getExtraData($vehicle),
            'age_identifier' => $vehicle->getAgeIdentifier(),
            'custom' => $vehicle->getAllCustom(),
            'monthly_price' => $vehicle->monthly_price,
            'monthly_cost_type' => $vehicle->getMonthlyCostType(),
            'engine_size_cc' => $vehicle->engine_size_cc,
            'is_vat_applicable' => $vehicle->is_vat_applicable,
            'coming_soon' => $vehicle->getComingSoonStatus(),
            'specs' => $vehicle->specs->map(fn($spec) => [
                'category' => $spec->category,
                'description' => $spec->description,
                'value' => $spec->value,
            ]),
            'features' => $vehicle->features->pluck('name'),
            'thumbnail' => [
                'small' => $this->getPreviewImage($vehicle)
            ]
        ];

        return $data;
    }

    private function getExtraData(Vehicle $vehicle)
    {
        return collect(event(new LoadVehicleDataFields($vehicle, 'ui')))
            ->filter()
            ->mapWithKeys(fn($field) => $field)
            ->merge($this->getCustomAttributes($vehicle));
    }

    private function trackViews(): void
    {
        $this->resource->each(
            fn(Vehicle $vehicle) => TrackResourceView::trackCompareView($vehicle)
        );
    }

    protected function largeImageDimensions(): string
    {
        return 'large';
    }

    protected function mediumImageDimensions(): string
    {
        return 'tile';
    }

    protected function thumbnailImageDimensions(): string
    {
        return 'tile';
    }

    protected function getFinanceExample(Vehicle $vehicle)
    {
        if (Settings::get('vehicle-list-load-finance-example')) {
            $type = Settings::get('vehicle-list-load-finance-example-type', 'cheapest');
            if ($type !== 'cheapest') {
                $example = $vehicle->financeExamples->where('finance_type', $type)->sortBy('monthly_price')->first();
                if ($example) {
                    $example->makeHidden([
                        'id',
                        'vehicle_id',
                        'provider',
                        'created_at',
                        'updated_at',
                    ]);
                    return $example;
                }
            }
            $vehicle->defaultFinanceExample?->makeHidden([
                'id',
                'vehicle_id',
                'provider',
                'created_at',
                'updated_at',
            ]);
            return $vehicle->defaultFinanceExample;
        }

        return null;
    }
}
