<?php

namespace App\Http\Resources\Traits;

use Mtc\MercuryDataModels\Media;

trait TransformsImageAttributesForAdmin
{
    /**
     * Transform image attributes for MediaUploader component.
     * Adds meta.selected with media data for each image type attribute.
     */
    protected function transformImageAttributesForAdmin(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['meta']['selected'] = collect($mediaIds)
                        ->map(fn($id) => $mediaItems->get((int) $id) ?? $mediaItems->get((string) $id))
                        ->filter()
                        ->map(fn($media) => [
                            'media' => [
                                'id' => $media->id,
                                'title' => $media->title,
                                'src' => $media->square_thumb_url,
                                'original_src' => $media->original_url,
                                'square_thumb_url' => $media->square_thumb_url,
                                'original_url' => $media->original_url,
                                'type' => $media->type,
                                'extension' => $media->extension,
                                'interior' => $media->interior ?? null,
                                'exterior' => $media->exterior ?? null,
                                'primary' => $media->primary ?? null,
                                'image_provider' => $media->image_provider ?? null,
                            ],
                        ])
                        ->values()
                        ->toArray();
                }
            }
            return $field;
        })->toArray();
    }
}
