<?php

namespace Daylight\Core\Modules\MediaLibrary\Console\Commands;

use Daylight\Core\Modules\MediaLibrary\Jobs\GenerateMediaConversionJob;
use Daylight\Core\Modules\MediaLibrary\Models\Media;
use Illuminate\Console\Command;

class RegenerateConversionsCommand extends Command
{
    protected $signature = 'daylight:media:regenerate-conversions 
                            {--media= : Specific media ID to regenerate conversions for}
                            {--force : Force regenerate all conversions, deleting existing ones}';

    protected $description = 'Regenerate media conversions for images';

    public function handle(): int
    {
        $mediaId = $this->option('media');
        $force = $this->option('force');

        if ($mediaId) {
            return $this->regenerateForMedia($mediaId, $force);
        }

        return $this->regenerateForAll($force);
    }

    protected function regenerateForMedia(int $mediaId, bool $force): int
    {
        $media = Media::query()->find($mediaId);

        if (! $media) {
            $this->error("Media with ID {$mediaId} not found.");

            return self::FAILURE;
        }

        if (! $media->isImage()) {
            $this->error('Media is not an image. Conversions are only available for images.');

            return self::FAILURE;
        }

        $this->info("Regenerating conversions for media ID {$mediaId}: {$media->name}");

        $this->regenerateConversions($media, $force);

        $this->info('Conversions queued successfully.');

        return self::SUCCESS;
    }

    protected function regenerateForAll(bool $force): int
    {
        $query = Media::query()->whereNotNull('path');

        $media = $query->get()->filter(fn ($m) => $m->isImage());

        if ($media->isEmpty()) {
            $this->info('No images found to process.');

            return self::SUCCESS;
        }

        $this->info("Found {$media->count()} image(s) to process.");

        $bar = $this->output->createProgressBar($media->count());
        $bar->start();

        $conversionsQueued = 0;

        foreach ($media as $item) {
            $queued = $this->regenerateConversions($item, $force);
            $conversionsQueued += $queued;
            $bar->advance();
        }

        $bar->finish();
        $this->newLine();

        $this->info("Queued {$conversionsQueued} conversion job(s) for {$media->count()} image(s).");

        return self::SUCCESS;
    }

    protected function regenerateConversions(Media $media, bool $force): int
    {
        $conversions = config('media.conversions', []);

        if ($force) {
            // Delete existing conversions
            foreach ($media->conversions as $conversion) {
                // Delete physical file
                if ($conversion->disk && $conversion->path) {
                    \Storage::disk($conversion->disk)->delete($conversion->path);
                }

                // Delete database record
                $conversion->delete();
            }
        }

        $queued = 0;

        foreach ($conversions as $conversionName => $config) {
            // Check if conversion already exists (only if not force mode)
            if (! $force) {
                $exists = $media->conversions()->where('name', $conversionName)->exists();
                if ($exists) {
                    continue;
                }
            }

            // Dispatch job
            GenerateMediaConversionJob::dispatch($media, $conversionName, $config);
            $queued++;
        }

        return $queued;
    }
}
