<?php

namespace App\Console\Commands;

use App\Services\Updater;
use Illuminate\Console\Command;

/**
 * One-time data migration for installs that predate the public/user-uploads
 * switch. Older versions stored local uploads in storage/app/public (served via
 * the public/storage symlink); the current `public` disk root is
 * public_path('user-uploads'). This MOVES the bytes so existing buyers' project
 * media / logo / favicon / theme assets keep resolving after an update.
 *
 * DB paths are RELATIVE (e.g. `branding/logo-x.png`) and resolve through the
 * active disk root, so no DB rewrite is needed — only the files move.
 *
 * Idempotent + resumable: once a file is moved it's gone from the old root, so
 * re-running is a no-op (or finishes a partial run). Skip-if-exists never
 * overwrites a file already present in the new location. Cloud-storage installs
 * are unaffected (files live in the bucket; this only touches the local dirs).
 *
 * Runs automatically after migrations in Updater::finalize() + runMigrations(),
 * and can be run by hand: `php artisan media:relocate-to-public-uploads`.
 */
class RelocateUploadsCommand extends Command
{
    protected $signature = 'media:relocate-to-public-uploads {--dry-run : Report what would move without moving}';

    protected $description = 'Move legacy storage/app/public uploads into public/user-uploads (one-time, idempotent).';

    public function handle(): int
    {
        $dry = (bool) $this->option('dry-run');

        if (! is_dir(storage_path('app/public'))
            || realpath(storage_path('app/public')) === realpath(public_path('user-uploads'))) {
            $this->info('No legacy uploads to relocate.');

            return self::SUCCESS;
        }

        $r = Updater::relocateLegacyUploads($dry);

        $prefix = $dry ? '[dry-run] ' : '';
        $this->info("{$prefix}Relocated {$r['moved']} file(s), skipped {$r['skipped']} existing, {$r['failed']} failed.");

        return $r['failed'] > 0 ? self::FAILURE : self::SUCCESS;
    }
}
