<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\BotActivation;
use Illuminate\Support\Facades\Log;

class RenewExpiredBots extends Command
{
    protected $signature = 'bots:renew-expired';
    protected $description = 'Automatically renew active AI bots before they expire so old users can continue using it';

    public function handle()
    {
        $this->info('Finding active bots that are about to expire...');
        
        // Find bots that are active and expiring within the next 3 days
        $active_expiring = BotActivation::where('status', 'active')
            ->where('expires_in', '<', time() + (3 * 86400))
            ->get();
            
        $this->info("Found {$active_expiring->count()} active bots about to expire.");
        Log::info("RenewExpiredBots: Found {$active_expiring->count()} active bots about to expire.");

        foreach ($active_expiring as $act) {
            // renew for another year
            $act->expires_in = $act->expires_in + (365 * 24 * 60 * 60); 
            $act->save();
            
            Log::info("Renewed bot activation ID {$act->id} for another year. New expiration: {$act->expires_in}");
        }

        $this->info('Renewal process complete.');
        return 0;
    }
}
