<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use App\Models\ItemPhoto;

class MigrateImagesToS3 extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'images:migrate-to-s3 {--dry-run : Show what would be migrated without actually doing it}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate existing item images from local storage to S3';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $dryRun = $this->option('dry-run');
        
        if ($dryRun) {
            $this->info('Running in DRY RUN mode - no files will be moved');
        }

        // Get all item photos
        $photos = ItemPhoto::all();
        
        if ($photos->count() === 0) {
            $this->info('No photos found to migrate.');
            return;
        }

        $this->info("Found {$photos->count()} photos to migrate.");
        
        $migrated = 0;
        $skipped = 0;
        $errors = 0;

        $progressBar = $this->output->createProgressBar($photos->count());
        $progressBar->start();

        foreach ($photos as $photo) {
            try {
                // Check if file exists locally
                if (!Storage::disk('public')->exists($photo->path)) {
                    $this->newLine();
                    $this->warn("Local file not found: {$photo->path}");
                    $skipped++;
                    $progressBar->advance();
                    continue;
                }

                // Check if already exists on S3 (skip S3 existence check due to permission issues)
                // We'll just try to upload and let S3 handle duplicates
                // if (Storage::disk('images')->exists($photo->path)) {
                //     $skipped++;
                //     $progressBar->advance();
                //     continue;
                // }

                if (!$dryRun) {
                    // Get file contents from local storage
                    $fileContents = Storage::disk('public')->get($photo->path);
                    
                    // Upload to S3
                    Storage::disk('images')->put($photo->path, $fileContents, 'public');
                    
                    // Update the photo record with new URL
                    $photo->url = Storage::disk('images')->url($photo->path);
                    $photo->save();
                    
                    // Optionally delete from local storage (commented out for safety)
                    // Storage::disk('public')->delete($photo->path);
                }

                $migrated++;
            } catch (\Exception $e) {
                $this->newLine();
                $this->error("Error migrating {$photo->path}: " . $e->getMessage());
                $errors++;
            }

            $progressBar->advance();
        }

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

        if ($dryRun) {
            $this->info("DRY RUN COMPLETE:");
            $this->info("Would migrate: {$migrated} photos");
            $this->info("Would skip: {$skipped} photos");
            $this->info("Errors: {$errors}");
        } else {
            $this->info("MIGRATION COMPLETE:");
            $this->info("Migrated: {$migrated} photos");
            $this->info("Skipped: {$skipped} photos");
            $this->info("Errors: {$errors}");
            
            if ($migrated > 0) {
                $this->newLine();
                $this->info("Local files have been preserved for safety.");
                $this->info("You can manually delete them from storage/app/public/items/ after verifying the migration.");
            }
        }

        return $errors === 0 ? 0 : 1;
    }
}