<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;
use Mtc\MercuryDataModels\Media;
use Symfony\Component\Console\Helper\ProgressBar;

class CreateJpgBackupForMedia extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'media:create-jpg-version';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Will create jpg version for the uploaded webp original';

    private ProgressBar $progress_bar;

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $count = Media::query()->whereNull('external')->count();
        $this->progress_bar = $this->output->createProgressBar($count);
        Media::query()
            ->whereHas('uses', fn($query) => $query->where('owner_type', 'vehicle')->whereHas('owner'))
            ->chunk(100, fn(Collection $chunk) => $chunk->each(fn(Media $media) => $this->process($media)));
    }

    private function process(Media $media): void
    {
        try {
            $this->progress_bar->advance();
            $image = (new ImageManager(Config::get('media.image_manager_config', [])))
                ->make(Storage::disk(Config::get('filesystems.default_media'))->get($media->path . '/' . $media->src));

            // store a copy in jpg for better handling with 3rd parties that do not support .webp
            Storage::disk(Config::get('filesystems.default_media'))
                ->put(
                    $media->path . '/' . str_replace('.webp', '.jpg', $media->src),
                    $image->stream('jpg'),
                    ['visibility' => 'public']
                );
        } catch (\Exception $exception) {
            $this->output->error($exception->getMessage());
        }
    }
}
