<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Namu\WireChat\Models\Conversation;

class UpdateExistingConversationsDisappearing extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wirechat:update-conversations-disappearing';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set disappearing_started_at for existing conversations without this field';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (!timebank_config('wirechat.disappearing_messages.enabled', true)) {
            $this->info('Disappearing messages feature is disabled');
            return Command::SUCCESS;
        }

        $this->info('Updating existing conversations...');

        // Find all conversations without disappearing_started_at or disappearing_duration set
        $conversations = Conversation::where(function($query) {
            $query->whereNull('disappearing_started_at')
                  ->orWhereNull('disappearing_duration');
        })->get();

        if ($conversations->isEmpty()) {
            $this->info('No conversations need updating');
            return Command::SUCCESS;
        }

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

        $count = 0;
        foreach ($conversations as $conversation) {
            $conversation->disappearing_started_at = now();
            $conversation->disappearing_duration = $duration;
            $conversation->save();
            $count++;
        }

        $this->info("Updated {$count} conversations with duration {$duration} seconds");

        return Command::SUCCESS;
    }
}
