<?php

namespace App\Console\Commands;

use App\Models\Environments\Type;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class MigrateTypeImagesToStorage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'types:migrate-images-to-storage';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migra las imágenes de tipos de entorno de public/ a storage/app/public/';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Migrando imágenes de tipos de entorno a storage...');

        $types = Type::whereNotNull('image')->get();
        $migrated = 0;
        $skipped = 0;
        $errors = 0;

        foreach ($types as $type) {
            $imagePath = $type->image;
            $publicPath = public_path($imagePath);
            $storagePath = storage_path("app/public/{$imagePath}");

            // Si la imagen existe en public pero no en storage
            if (File::exists($publicPath) && !Storage::disk('public')->exists($imagePath)) {
                try {
                    // Asegurar que el directorio existe en storage
                    $directory = dirname($imagePath);
                    Storage::disk('public')->makeDirectory($directory);

                    // Copiar la imagen a storage
                    Storage::disk('public')->put($imagePath, File::get($publicPath));
                    
                    $this->line("✓ Migrada: {$imagePath}");
                    $migrated++;
                } catch (\Exception $e) {
                    $this->error("✗ Error migrando {$imagePath}: " . $e->getMessage());
                    $errors++;
                }
            } elseif (Storage::disk('public')->exists($imagePath)) {
                $this->line("- Ya existe en storage: {$imagePath}");
                $skipped++;
            } elseif (!File::exists($publicPath)) {
                $this->warn("⚠ No encontrada en public ni storage: {$imagePath}");
                $skipped++;
            }
        }

        $this->newLine();
        $this->info("Migración completada:");
        $this->line("  - Migradas: {$migrated}");
        $this->line("  - Omitidas: {$skipped}");
        if ($errors > 0) {
            $this->error("  - Errores: {$errors}");
        }

        return Command::SUCCESS;
    }
}
