<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Http\Resources\Traits\TransformsImageAttributesForDisplay;
use App\Traits\GetsFormResource;
use App\Traits\MediaHasSizes;
use App\Traits\RetrievesContent;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Traits\HasVehicleCustomAttributes;
use Mtc\MercuryDataModels\VehicleTrim;

class VehicleTrimResource extends JsonResource
{
    use RetrievesContent;
    use MediaHasSizes;
    use HasVehicleCustomAttributes;
    use TransformsImageAttributesForDisplay;
    use GetsFormResource;

    public static $wrap = '';

    private const UI_RESOURCE_PREFIX = 'App\\Http\\Resources\\';

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request): array
    {
        $this->resource->load([
            'mediaUses.media',
            'make',
            'model',
            'content.mediaUses.media',
            'content.subContent.mediaUses.media',
            'content.subContent.subContent.mediaUses.media',
            'content.subContent.subContent.subContent.mediaUses.media',
            'content.contentElement',
            'content.globalContent.contentElement',
            'content.subContent.contentElement',
            'content.subContent.globalContent.contentElement',
            'content.subContent.subContent.contentElement',
            'content.subContent.subContent.globalContent.contentElement',
            'content.subContent.subContent.subContent.contentElement',
            'content.subContent.subContent.subContent.globalContent.contentElement',
            'newCar.mediaUses.media',
        ]);

        $resource = [
            'id' => $this->resource->id,
            'name' => $this->resource->name,
            'make_name' => $this->resource->make?->name,
            'make_slug' => $this->resource->make?->slug,
            'model_name' => $this->resource->model?->name,
            'model_slug' => $this->resource->model?->slug,
            'new_car_slug' => $this->resource->newCar?->slug,
            'description' => $this->resource->description,
            'fuel_types' => $this->resource->fuel_types,
            'colours' => $this->resource->colours,
            'transmission_types' => $this->resource->transmission_types,
            'mpg' => $this->resource->mpg,
            'emissions' => $this->resource->emissions,
            'engine_size' => $this->resource->engine_size,
            'battery_size' => $this->resource->battery_size,
            'range_miles' => $this->resource->range_miles,
            'battery_charge_time' => $this->resource->battery_charge_time,
            'battery_quick_charge_time' => $this->resource->battery_quick_charge_time,
            'bhp' => $this->resource->bhp,
            'ps' => $this->resource->ps,
            'zero_to_sixty' => $this->resource->zero_to_sixty,
            'zero_to_sixty_two' => $this->resource->zero_to_sixty_two,
            'doors' => $this->resource->doors,
            'seats' => $this->resource->seats,
            'wheelbase' => $this->resource->wheelbase,
            'full_price' => $this->resource->full_price,
            'data' => $this->resource->data,
        ];

        $resource['image'] = $this->getMedia(true, $this->resource);
        $resource['listing_image'] = $this->getMedia(false, $this->resource);
        $resource['content'] = $this->getContent($this->resource->content);
        $resource['seo'] = $this->fillSeo('vehicle-trim', $request->header('x-path') ?? $this->resource->urlPath());

        $resource['custom'] = $this->resource->getAllCustom();
        $resource['forms'] = [
            'enquire' => $this->getTrimForm(),
        ];

        $newCar = $this->resource->newCar;
        $resource['trims'] = $newCar
            ? $newCar->getTrims()
                ->where('id', '!=', $this->resource->id)
                ->map(fn(VehicleTrim $trim) => array_merge(
                    $trim->toArray(),
                    [
                        'image' => $this->getMedia(true, $trim)->first(),
                        'listing_image' => $this->getMedia(false, $trim)->first(),
                        'custom' => $trim->getAllCustom(),
                    ]
                ))
                ->values()
            : [];

        return $resource;
    }

    private function getTrimForm(): ?FormViewResource
    {
        $formId = Settings::get('vehicle-trim-enquiry-form-id');
        if (empty($formId)) {
            return null;
        }

        $form = Form::query()
            ->with('sections.questions')
            ->find($formId);

        $newCar = $this->resource->newCar;

        return $this->getResourceForForm($form, array_filter([
            'new_car_id' => $newCar?->id,
            'dealership_id' => $newCar?->dealership_id,
            'franchise_id' => $newCar?->franchise_id,
        ]));
    }

    private function getMedia(bool $primary, ?VehicleTrim $model = null): Collection
    {
        return $model->mediaUses
            ->where('primary', $primary)
            ->map(function (MediaUse $mediaUse) use ($model) {
                $mediaUse->setOverrideOwnerType('new-car');
                return [
                    'id' => $mediaUse->id,
                    'hex1' => $mediaUse->media->hex1,
                    'hex2' => $mediaUse->media->hex2,
                    'title' => $mediaUse->title,
                    'alt_text' => $mediaUse->alt_text,
                    'description' => $mediaUse->description,
                    'caption' => $mediaUse->caption,
                    'src' => $mediaUse->getUrl('full-width-banner'),
                    'sizes' => $this->allSizesForUse($model, $mediaUse),
                ];
            })
            ->values();
    }
}
