<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Facades\Fields;
use Mtc\ContentManager\Http\Resources\MediaEntryResource;
use Mtc\MercuryDataModels\PropertyAttributeValue;
use Mtc\MercuryDataModels\PropertyCategoryField;

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

    /**
     * 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('category.fields');
        $this->resource->fields = $this->getCustomAttributes();
        $this->resource->canonical = $this->resource->data['canonical'] ?? null;
        return parent::toArray($request);
    }

    private function getCustomAttributes()
    {
        $this->resource->load('attributeValues.mediaUses.media');
        return $this->resource->category->fields
            ->map(fn(PropertyCategoryField $attribute) => $this->allocateAttributeValues($attribute));
    }

    private function allocateAttributeValues(PropertyCategoryField $attribute)
    {
        $value = $this->resource->attributeValues->where('field_id', $attribute->id)->first();
        if ($attribute->type === 'image' && $value) {
            $this->imageMeta($attribute, $value);
        }
        return [
            'id' => $attribute->id,
            'name' => $attribute->name,
            'slug' => $attribute->slug,
            'type' => $attribute->type,
            'component' => 'EditableContent' . Fields::field($attribute->type)->getComponent(),
            'value' => $value?->getValue(),
            'meta' => $attribute->data,
        ];
    }

    private function imageMeta(PropertyCategoryField $field, PropertyAttributeValue $attribute): void
    {
        $meta = $field->data ?? [];
        $meta['selected'] = $attribute->mediaUses?->map(fn(MediaUse $mediaUse) => new MediaEntryResource($mediaUse));
        $field->data = $meta;
    }
}
