<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Http\Resources\MediaEntryResource;
use Mtc\MercuryDataModels\CarConfiguratorExtra;
use Mtc\MercuryDataModels\CarConfiguratorModel;
use Mtc\MercuryDataModels\CarConfiguratorPackage;
use Mtc\MercuryDataModels\DrivetrainType;
use Mtc\MercuryDataModels\FuelType;
use Mtc\MercuryDataModels\TransmissionType;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;

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

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $this->resource->load([
            'make',
            'model',
            'sections',
            'trims.restrictions',
            'engines.restrictions',
            'colours.restrictions',
            'wheels.restrictions',
            'interiors.restrictions',
            'packages.restrictions',
            'extras.restrictions',
            'custom.restrictions',
            'editions.mediaUses.media',
            'trims.mediaUses.media',
            'engines.mediaUses.media',
            'colours.mediaUses.media',
            'wheels.mediaUses.media',
            'interiors.mediaUses.media',
            'packages.mediaUses.media',
            'extras.mediaUses.media',
            'custom.mediaUses.media',
        ]);

        $this->resource->sections = $this->resource->sections
            ->each(function ($section) {
                $section->edit = false;
                $section->object_type = $section->custom ? 'Custom' : Str::singular($section->name);
                $section->data = $section->data ?? ['interior' => false, 'exterior' => false];
            });
        $resource = $this->resource->toArray();
        $existing_restrictions = $this->resource->restrictions()
            ->whereIn('functionality_type', ['packages', 'extras'])
            ->get()
            ->groupBy('functionality_type')
            ->map(fn($group) => $group->groupBy('functionality_id'));
        foreach (CarConfiguratorModel::$relationship_models as $relationship) {
            $resource[$relationship] = $this->resource[$relationship]
                ->map(function ($related) use ($relationship, $existing_restrictions) {
                    if (in_array($relationship, ['packages', 'extras'])) {
                        return array_merge(
                            $related->pivot->toArray(),
                            ['restrictions' => $existing_restrictions[$relationship][$related->id] ?? []]
                        );
                    }
                    $data = $related->toArray();
                    $data['media'] = $related->mediaUses->pluck('media_id');
                    $data['media_uses'] = $related->mediaUses
                        ->map(fn(MediaUse $mediaUse) => new MediaEntryResource($mediaUse));
                    return $data;
                });
        }

        return [
            'configurator' => $resource,
            'makes' => VehicleMake::query()->with('filterIndex')->select(['id', 'name'])->get(),
            'models' => VehicleModel::query()
                ->with('filterIndex')
                ->where('make_id', $this->resource->make_id)
                ->select(['id', 'name'])
                ->get(),
            'packages' => CarConfiguratorPackage::query()->get()
                ->groupBy(fn($entry) => $entry->category ?? __('labels.no_category')),
            'extras' => CarConfiguratorExtra::query()->get()
                ->groupBy(fn($entry) => $entry->category ?? __('labels.no_category')),
            'drivetrains' => DrivetrainType::query()->with('filterIndex')->select(['id', 'name'])->get(),
            'transmissions' => TransmissionType::query()->with('filterIndex')->select(['id', 'name'])->get(),
            'fuel_types' => FuelType::query()
                ->with('filterIndex')
                ->select(['id', 'name', 'mpg_data', 'ev_data'])
                ->get(),

        ];
    }
}
