<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Traits\HasPlaceholderImage;
use Carbon\Carbon;
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\Vehicle;
use Mtc\MercuryDataModels\VehicleView;

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,
            '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
    {
        /** @var Collection $ids */
        $ids = $this->resource->pluck('id');
        $existing = VehicleView::query()
            ->whereIn('vehicle_id', $ids)
            ->where('date', Carbon::now()->format('Y-m-d'))
            ->pluck('vehicle_id');

        $missing = $ids->reject(fn($id) => $existing->search($id));

        if ($missing->isNotEmpty()) {
            $data = $missing->map(fn ($id) => [
                'vehicle_id' => $id,
                'hits' => 0,
                'compare_views' => 1,
                'date' => Carbon::now()->format('Y-m-d'),
            ]);
            VehicleView::query()->upsert($data->toArray(), ['vehicle_id', 'date']);
        }

        VehicleView::query()
            ->whereIn('vehicle_id', $existing)
            ->increment('compare_views');
    }

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

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

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