<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\CloudflareR2Service;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MigrateDocsToR2 extends Command
{
    protected $signature = 'docs:migrate-to-r2 
                            {--from= : Fecha inicio (formato: Y-m-d)}
                            {--to= : Fecha fin (formato: Y-m-d)}
                            {--dry-run : Solo simula, no sube nada}';

    protected $description = 'Sube archivos locales a Cloudflare R2 en /documentsign filtrado por rango de fechas';

    public function handle()
    {
        $from   = $this->option('from');
        $to     = $this->option('to');
        $dryRun = $this->option('dry-run');

        // Validar que ambas fechas estén presentes
        if (!$from || !$to) {
            $this->error('Debes indicar --from y --to. Ejemplo: --from=2024-01-01 --to=2024-12-31');
            return 1;
        }

        $this->info("Rango de fechas: {$from} al {$to}");

        $records = DB::table('documents')
                      ->select('id_document', 'pathpdf', 'uuidpdf', 'datetime')
                      ->whereNotNull('pathpdf')
                      ->whereBetween('datetime', [$from . ' 00:00:00', $to . ' 23:59:59'])
                      ->get();

        if ($records->isEmpty()) {
            $this->warn('No se encontraron registros en ese rango de fechas.');
            return 0;
        }

        $this->info("Total de archivos a procesar: {$records->count()}");

        if ($dryRun) {
            $this->warn('MODO DRY-RUN: No se subirá nada.');
        }

        $r2Service = new CloudflareR2Service();
        $success   = 0;
        $failed    = 0;
        $skipped   = 0;

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

        foreach ($records as $record) {
           $localPath = rtrim($record->pathpdf, '/') . '.pdf';
            $id        = $record->id_document;
            $uuid      = $record->uuidpdf;

            if (!file_exists($localPath)) {
                $this->newLine();
                $this->warn("  [SKIP] Archivo no encontrado: {$localPath} (ID: {$id})");
                $skipped++;
                $bar->advance();
                continue;
            }

            // Usa el uuidpdf como nombre del archivo en R2
            $r2Key = 'documentsign/' . $uuid . '.pdf';

            try {
                if (!$dryRun) {
                  //  $stream = fopen($localPath, 'r');
                    $r2Service->subirArchivoLocal($r2Key, $localPath);
                  //  fclose($stream);
                }

                $success++;
                Log::info("Subido a R2: {$r2Key}", ['id' => $id, 'uuid' => $uuid]);

            } catch (\Exception $e) {
                $failed++;
                $this->newLine();
                $this->error("  [ERROR] ID {$id} | UUID {$uuid}: {$e->getMessage()}");
                Log::error("Error subiendo a R2", [
                    'id'    => $id,
                    'uuid'  => $uuid,
                    'path'  => $localPath,
                    'error' => $e->getMessage()
                ]);
            }

            $bar->advance();
            usleep(50000);
        }

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

        $this->table(
            ['Resultado', 'Cantidad'],
            [
                ['Exitosos', $success],
                ['Fallidos', $failed],
                ['Omitidos', $skipped],
                ['Total',    $records->count()],
            ]
        );

        return 0;
    }
}