<?php

namespace App\Http\Resources;

use Carbon\Carbon;
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
     */
    #[\Override]
    public function toArray($request)
    {
        $this->resource->load('category.fields');
        $this->resource->fields = $this->getCustomAttributes();
        $this->resource->canonical = $this->resource->data['canonical'] ?? null;
        $resource = parent::toArray($request);

        $resource['created_at'] = Carbon::parse($this->resource->created_at)->format('d/m/Y H:i');
        $resource['updated_at'] = Carbon::parse($this->resource->updated_at)->format('d/m/Y H:i');

        return $resource;
    }

    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): array
    {
        $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;
    }
}
