<?php

namespace App\Traits;

use App\Http\Resources\FormViewResource;
use App\ShortcodeHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Models\MediaSize;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\Vehicle;

trait MapElementBasedContent
{
    private function mapContent(Model $resource, array $entry, Request $request, string $type): array
    {
        if (isset($entry['field_type']) && in_array($entry['field_type'], ['form', 'form-field'])) {
            $vehicleId = $request->input('vehicle_id');
            $dealershipId = $request->input('dealership_id')
                ?? ($vehicleId ? Vehicle::query()->find($vehicleId)?->dealership_id : null);

            $entry['content'] = new FormViewResource(Form::query()->find($entry['content']))
                ->setValues([
                    'offer_id' => $request->input('offer_id'),
                    'vehicle_id' => $vehicleId,
                    'dealership_id' => $dealershipId,
                    'page_id' => $request->input('page_id'),
                    'valuation_id' => $request->input('valuation_id'),
                ]);
        }

        if (isset($entry['field_type']) && in_array($entry['field_type'], ['text', 'editor'])) {
            $entry['content'] = ShortcodeHelper::replaceShortcodes($entry['content']);
        }

        if (isset($entry['field_type']) && $entry['field_type'] === 'image') {
            $entry['content'] = $resource->mediaUses
                ->filter(fn (MediaUse $mediaUse) => in_array($mediaUse->media_id, $entry['content'] ?? []))
                ->values()
                ->map(fn (MediaUse $mediaUse) => [
                    'src' => $mediaUse->getUrl('square-tile'),
                    'alt' => $mediaUse->alt_text,
                    'id' => $mediaUse->id,
                    'title' => $mediaUse->title,
                    'alt_text' => $mediaUse->alt_text,
                    'description' => $mediaUse->description,
                    'caption' => $mediaUse->caption,
                    'sizes' => $this->allSizesForUse($resource, $mediaUse, $type)
                        ->put('original', $mediaUse->media->getOriginalUrlAttribute()),
                    'type' => $mediaUse->media->type,
                    'interior' => $mediaUse->interior,
                    'exterior' => $mediaUse->exterior,
                    'hex1' => $mediaUse->media?->hex1,
                    'hex2' => $mediaUse->media?->hex2,
                ]);
        }
        if (!empty($entry['children'])) {
            $entry['children'] = collect($entry['children'])
                ->map(fn ($child) => $this->mapContent($resource, $child, $request, $type));
        }

        return collect($entry)
            ->forget([
                'id',
                'editable',
                'optionsMenuVisible',
                'nestable',
                'nestedLimit',
                'repeatable',
                'icon',
                'component',
                'componentName',
                'data',
                'meta',
                'error',
            ])
            ->toArray();
    }
    private function allSizesForUse(Model $content, MediaUse $mediaUse, string $type): Collection
    {
        $this->mediaSizes = Cache::remember(
            tenant('id') . '-media-size-collection-' . $type,
            now()->addHour(),
            fn () => MediaSize::query()->where('model', $type)->get()
        );

        return collect($mediaUse->allowed_sizes ?? [])
            ->reject(fn ($value, $key) => !is_numeric($key))
            ->keyBy(fn ($size) => $size)
            ->map(fn ($size) => $mediaUse->getUrl($size))
            ->merge($this->mediaSizes
                ->keyBy('label')
                ->map(fn (MediaSize $size) => $mediaUse->getUrl($size->label)))
            ->put('original', $mediaUse->media->getOriginalUrlAttribute());
    }
}
