<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Models\MediaSize;

trait MediaHasSizes
{
    private function allSizesForUse(Model $model, MediaUse $mediaUse): Collection
    {
        $this->mediaSizes = Cache::remember(
            tenant('id') . '-media-size-collection-' . $mediaUse->getOwnerType(),
            now()->addHour(),
            fn () => MediaSize::query()->where('model', $mediaUse->getOwnerType())->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)));
    }
}
