<?php

namespace App\Http\Resources\Traits;

use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Media;

trait TransformsImageAttributesForDisplay
{
    /**
     * Transform image attributes for frontend display.
     * Replaces value with gallery format data (matching HasPlaceholderImage::getGallery).
     */
    protected function transformImageAttributesForDisplay(Collection|array $extra): array
    {
        return collect($extra)->map(function ($field) {
            if (($field['type'] ?? null) === 'image') {
                $mediaIds = collect($field['value'] ?? [])->pluck('value')->filter()->values()->toArray();
                if (!empty($mediaIds)) {
                    $mediaItems = Media::whereIn('id', $mediaIds)->get()->keyBy('id');
                    $field['value'] = collect($mediaIds)
                        ->map(fn ($id) => $mediaItems->get((int) $id) ?? $mediaItems->get((string) $id))
                        ->filter()
                        ->map(fn ($media) => [
                            'id' => $media->id,
                            'title' => $media->title,
                            'alt_text' => $media->alt_text,
                            'description' => $media->description,
                            'caption' => $media->caption,
                            'src_large' => $media->original_url,
                            'src_medium' => $media->square_thumb_url,
                            'src_thumbnail' => $media->square_thumb_url,
                            'sizes' => [
                                'original' => $media->original_url,
                            ],
                            'type' => $media->type,
                            'provider' => $media->image_provider,
                            'interior' => null,
                            'exterior' => null,
                            'hex1' => $media->hex1,
                            'hex2' => $media->hex2,
                        ])
                        ->values()
                        ->toArray();
                } else {
                    $field['value'] = [];
                }
            }
            return $field;
        })->toArray();
    }
}
