<?php

namespace App\Http\Resources;

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

class MediaListResource extends \Mtc\ContentManager\Http\Resources\MediaListResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $data = parent::toArray($request);

        $data['type_filter_options'] = $this->getMediaTypeFilters();

        return $data;
    }

    /**
     * Map media record values to have all needed details
     *
     * @param Media $media
     * @return Media
     */
    private function mapMedia(Media $media)
    {
        $media->extension = pathinfo($media->src, PATHINFO_EXTENSION);
        return $media;
    }

    private function getMediaTypeFilters(): Collection
    {
        if (tenant('type') === 'listing') {
            return collect();
        }

        $mediaTypeFilters = collect(config('media.media_type_filters'));
        $existingTypes = Media::query()
            ->distinct()
            ->pluck('type')
            ->toArray();
        return $mediaTypeFilters
            ->only($existingTypes)->map(function ($label, $key) {
                return [
                    'name' => $label,
                    'id' => $key,
                    'value' => $key,
                ];
            })->prepend([
                'name' => 'All',
                'id' => 'all',
                'value' => '',
            ])->values();
    }
}
