<?php

namespace App\Console\Commands;

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

class ConvertLegacyMediaFilesToNonLegacy extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'media:convert-legacy-files';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Convert files from legacy structure to new format';

    private bool $move = false;

    private ProgressBar $progressBar;

    public function handle()
    {
        if (empty(tenant('id'))) {
            $this->output->error('Please run for a tenant');
            return self::FAILURE;
        }

        $this->move = $this->confirm('Perform live migration (if no it will perform dry run)?');

        $count = Media::query()
            ->where('type', '!=', 'image')
            ->whereNull('external')
            ->where('legacy_structure', 1)
            ->count();
        $this->output->info("$count entries to convert");
        $this->progressBar = $this->output->createProgressBar($count);

        Media::query()
            ->where('type', '!=', 'image')
            ->where('legacy_structure', 1)
            ->whereNull('external')
            ->chunk(100, fn(Collection $chunk) => $chunk->each(fn(Media $item) => $this->migrateFile($item)));
        return self::SUCCESS;
    }

    private function migrateFile(Media $item): void
    {
        $source_path = $item->path . '/' . $item->src;
        $destination = tenant('id') . '/' . $item->path;
        $destination_path = $destination . '/' . $item->src;

        if ($this->move) {
            $this->progressBar->advance();
            Storage::disk('media')->move($source_path, $destination_path);
            $item->path = $destination;
            $item->legacy_structure = null;
            $item->save();
        } else {
            $this->output->info("Moving original from $source_path to $destination_path");
        }
    }
}
