<?php

namespace App\Http\Resources;

use App\Traits\RetrievesFieldData;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Mtc\ContentManager\Contracts\ContentElementField;
use Mtc\ContentManager\Http\Resources\ContentElementView as BaseContentElementView;
use Mtc\ContentManager\Models\MediaSize;
use Mtc\MercuryDataModels\ContentElement;

class ContentElementView extends BaseContentElementView
{
    use RetrievesFieldData;

    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('fields.childElement');
        $resource = $this->resource->toArray();
        $resource['nestable'] = $this->resource->data['nestable'] ?? false;
        $resource['nested_limit'] = $this->resource->data['nested_limit'] ?? null;
        $resource['repeatable'] = $this->resource->data['repeatable'] ?? false;
        $resource['fields'] = $this->resource->fields->map(fn($field) => $this->mapField($field));
        $blockResource = config('pages.content_element_block_resource');
        if (!empty($this->resource->preview_image)) {
            $resource['preview_image'] = [
                'url' => Storage::disk(Config::get('filesystems.default_media'))->url($this->resource->preview_image),
                'path' => $this->resource->preview_image,
            ];
        }

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

        if ($request->has('bare')) {
            return [
                'data' => $resource
            ];
        }

        return [
            'data' => $resource,
            'primitives' => collect(config('pages.field_types', []))
                ->map(fn($type) => App::make($type))
                ->values(),
            'elements' => new $blockResource(ContentElement::query()
                ->with('fields.childElement.fields.childElement.fields.childElement.fields')
                ->where('id', '!=', $this->resource->id)
                ->limit(10)
                ->get()),
            'categories' => config('pages.block_categories', []),
        ];
    }

    private function mapField(ContentElementField $field)
    {
        return [
            'id' => $field->id,
            'name' => $field->name,
            'icon' => $this->getFieldIcon($field) ?? $field->data['icon'],
            'field_type' => $field->field_type,
            'child_element_id' => $field->child_element_id,
            'data' => $field->data,
            'nestable' => $field->data['nestable'] ?? false,
            'isGroup' => $field->data['isGroup'] ?? false,
            'nestedLimit' => $field->data['nestedLimit'] ?? null,
            'editable' => $field->data['editable'] ?? false,
            'repeatable' => $field->data['repeatable'] ?? false,
            'optionsMenuVisible' => false,
            'meta' => $field->meta,
            'children' => [],
            'component' => $this->getField($field->field_type)?->getComponent(),
            'componentName' => $this->getField($field->field_type)?->getComponent(),
            'mediaSizeOptions' => $field->field_type == 'image'
                ? MediaSize::query()
                    ->orderBy('label')
                    ->get()
                    ->map(fn($mediaSize) => [
                        'id' => $mediaSize->dimensions,
                        'name' => $mediaSize->name,
                    ])
                    ->unique('id')
                    ->values()
                : [],
        ];
    }
}
