<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Model\Master\RvmCdrLog;
use App\Model\Master\RvmQueueList;
use Carbon\Carbon;

class RestartRvmCdrLog extends Command
{
    protected $signature = 'app:send:restart-rvm-cdr-log {--clientId=}';
    protected $description = 'Restart up to 50 RVM CDR log records with missing status.';

    public function handle()
    {
        $this->info("Starting RestartRvmCdrLog process...");

        $startDate = '2025-10-01 00:00:00';
        $thresholdTime = Carbon::now()->subMinutes(15);

        // Build query
        $query = RvmCdrLog::where('api_token', 'bc6c')
            ->where('tries', 1)
            ->whereNull('status')
            ->where('updated_at', '<', $thresholdTime)
            ->where('created_at', '>=', $startDate)
            ->orderByDesc('id')
            ->limit(50);

        // Optional client filter
        if ($clientId = $this->option('clientId')) {
            $query->where('client_id', $clientId);
        }

        $logs = $query->get();

        if ($logs->isEmpty()) {
            $this->info("No records found to update.");
            return;
        }

        $this->info("Found {$logs->count()} records. Processing...");

        foreach ($logs as $log) {
            // Delete related queue record (if any)
            RvmQueueList::where('rvm_cdr_log_id', $log->id)->delete();

            // Reset tries to 0
            $log->tries = 0;
            $log->save();

            $this->info("✅ Updated Log ID: {$log->id} (tries reset to 0)");
        }

        $this->info("🎯 Completed updating {$logs->count()} RVM CDR records successfully.");
    }
}
