<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Namu\WireChat\Models\Conversation;

class FixConversationDurations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wirechat:fix-conversation-durations {--dry-run : Show what would be fixed without making changes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix conversations with incorrect disappearing_duration values (exceeding INT max)';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Checking for conversations with invalid disappearing_duration values...');

        // Get correct duration in seconds from config
        $durationInDays = timebank_config('wirechat.disappearing_messages.duration', 30);
        $correctDuration = $durationInDays * 86400; // Convert days to seconds

        // Maximum value for signed INT in MySQL (2,147,483,647)
        $maxIntValue = 2147483647;

        // Find conversations with duration that exceeds INT max or is suspiciously large
        $conversations = Conversation::where('disappearing_duration', '>', $maxIntValue)
            ->orWhere('disappearing_duration', '>', 100000000) // Suspiciously large (> 1157 days)
            ->get();

        if ($conversations->isEmpty()) {
            $this->info('No conversations with invalid durations found.');
            return Command::SUCCESS;
        }

        $this->warn("Found {$conversations->count()} conversations with invalid durations:");
        $this->newLine();

        $table = [];
        foreach ($conversations as $conversation) {
            $table[] = [
                'ID' => $conversation->id,
                'Current Duration' => number_format($conversation->disappearing_duration),
                'Correct Duration' => number_format($correctDuration),
                'Started At' => $conversation->disappearing_started_at ? $conversation->disappearing_started_at->format('Y-m-d H:i') : 'NULL',
            ];
        }

        $this->table(['ID', 'Current Duration', 'Correct Duration', 'Started At'], $table);

        if ($this->option('dry-run')) {
            $this->info('Dry-run mode: No changes made.');
            $this->info("Would update {$conversations->count()} conversations to duration: {$correctDuration} seconds ({$durationInDays} days)");
            return Command::SUCCESS;
        }

        if (!$this->confirm("Update {$conversations->count()} conversations to duration {$correctDuration} seconds ({$durationInDays} days)?", true)) {
            $this->comment('Update cancelled.');
            return Command::SUCCESS;
        }

        $count = 0;
        foreach ($conversations as $conversation) {
            try {
                $conversation->disappearing_duration = $correctDuration;
                $conversation->save();
                $count++;
            } catch (\Exception $e) {
                $this->error("Failed to update conversation {$conversation->id}: " . $e->getMessage());
            }
        }

        $this->info("✓ Successfully updated {$count} conversations");
        $this->info("Duration set to: {$correctDuration} seconds ({$durationInDays} days)");

        return Command::SUCCESS;
    }
}
