<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Contracts\MediaUse;
use App\MediaRepository;

class ProcessMediaUseChunkJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(protected readonly Collection $chunk, private readonly MediaRepository $repository)
    {
        $this->onQueue('media');
    }

    public function handle()
    {
        $this->chunk
            ->load(['owner', 'media'])
            ->filter(fn(MediaUse $mediaUse) => $mediaUse->owner)
            ->each(fn(MediaUse $mediaUse) => $this->repository
                ->triggerSizeGenerationForMedia(
                    $mediaUse->media,
                    $this->repository->getAllowedSizes($mediaUse->owner, ['allowed_sizes' => $mediaUse->allowed_sizes]),
                    $mediaUse->owner
                ));
    }
}
