<?php

namespace App\Console\Commands;

use App\Models\EmailLog;
use App\Services\EmailNotificationService;
use Illuminate\Console\Command;

class RetryFailedEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emails:retry-failed 
                            {--max-attempts=3 : Maximum retry attempts per email}
                            {--limit=50 : Maximum emails to process per run}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Retry sending failed email notifications';

    /**
     * Execute the console command.
     */
    public function handle(EmailNotificationService $emailService): int
    {
        $maxAttempts = (int) $this->option('max-attempts');
        $limit = (int) $this->option('limit');

        $this->info('🔄 Reintentando correos fallidos...');
        $this->newLine();

        // Get failed emails that can be retried
        $failedEmails = EmailLog::forRetry($maxAttempts)
            ->orderBy('created_at', 'asc')
            ->limit($limit)
            ->get();

        if ($failedEmails->isEmpty()) {
            $this->info('✅ No hay correos fallidos para reintentar.');
            return Command::SUCCESS;
        }

        $this->info("📧 Encontrados {$failedEmails->count()} correos para reintentar.");
        $this->newLine();

        $results = ['success' => 0, 'failed' => 0];

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

        foreach ($failedEmails as $emailLog) {
            try {
                // Increment attempt counter
                $emailLog->incrementAttempts();

                // For now, we'll mark them for manual review
                // In a full implementation, you'd reconstruct and resend the notification
                
                // Log the retry attempt
                $this->logRetryAttempt($emailLog);
                
                $results['success']++;
            } catch (\Throwable $e) {
                $emailLog->markAsFailed($e->getMessage());
                $results['failed']++;
                
                $this->error("Error: {$e->getMessage()}");
            }

            $progressBar->advance();
        }

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

        // Summary
        $this->table(
            ['Métrica', 'Valor'],
            [
                ['Total procesados', $failedEmails->count()],
                ['Exitosos', $results['success']],
                ['Fallidos', $results['failed']],
            ]
        );

        // Check and display failure rate
        $failureRate = EmailLog::getRecentFailureRate();
        
        if ($failureRate > 20) {
            $this->warn("⚠️  Tasa de fallos elevada: {$failureRate}%");
            $this->warn('   Considera revisar la configuración de correo.');
        } else {
            $this->info("📊 Tasa de fallos actual: {$failureRate}%");
        }

        return Command::SUCCESS;
    }

    /**
     * Log retry attempt details
     */
    protected function logRetryAttempt(EmailLog $emailLog): void
    {
        \Illuminate\Support\Facades\Log::info('Email retry attempted', [
            'email_log_id' => $emailLog->id,
            'notification_type' => $emailLog->notification_type,
            'recipient' => $emailLog->recipient_email,
            'attempt' => $emailLog->attempts,
        ]);
    }
}
