<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\MenuEntry;

class MenuResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        if (is_array($this->resource)) {
            return $this->resource;
        }

        if (empty($this->resource)) {
            return $this->resource;
        }

        if (!$this->resource->relationLoaded('rootEntries')) {
            $this->resource->load([
                'element.fields',
                'rootEntries.children.children.children',
                'rootEntries.mediaUses.media'
            ]);
        }

        return $this->resource->rootEntries
            ->filter(fn($entry) => $entry->is_enabled)
            ->map(fn ($entry) => $this->mapEntry($entry, true))
            ->values()
            ->toArray();
    }

    private function mapEntry($entry, bool $topLevel = false): array
    {
        return [
            'name' => $entry->name,
            'url' => $entry->url ?? '',
            'content' => $topLevel ? $this->getContent($entry) : [],
            'css_class' => $entry->css_class,
            'external' => $entry->external,
            'data' => is_string($entry->data) ? json_decode($entry->data) : $entry->data,
            'children' => $entry->children
                ? $entry->children
                    ->filter(fn($entry) => $entry->is_enabled)
                    ->map(fn ($childEntry) => $this->mapEntry($childEntry))
                    ->values()
                : []
        ];
    }

    private function getFields()
    {
        return $this->resource->element->fields ?? collect([]);
    }

    private function getContent(MenuEntry $entry)
    {
        return $this->getFields()
            ->keyBy(fn($field) => str_replace('-', '_', $field->slug))
            ->map(function ($field) use ($entry) {
                if ($field->field_type === 'image') {
                    $mediaUse = $entry->mediaUses->first();
                    return $mediaUse ? [
                        'title' => $mediaUse->title,
                        'alt_text' => $mediaUse->alt_text,
                        'description' => $mediaUse->description,
                        'caption' => $mediaUse->caption,
                        'src_medium' => $mediaUse->getUrl('square-tile'),
                        'type' => $mediaUse->media->type
                    ] : [];
                }
                return $entry->content[$field->slug] ?? null;
            });
    }
}
