<?php

namespace App\Nexus\Console\Commands;

use App\Nexus\Engine\NexusConfig;
use App\Nexus\Engine\SessionController;
use App\Nexus\Models\NexusSession;
use Carbon\Carbon;
use Illuminate\Console\Command;

/**
 * Opens and closes trading sessions on schedule.
 * Runs every minute via Laravel scheduler.
 *
 * When nexus_status = inactive: exits silently, does nothing.
 * When emergency_pause = true: exits silently, sessions freeze.
 *
 * Auto-completes orphaned sessions stuck in "processing" for over 2 hours.
 * This prevents sessions from appearing stuck in the dashboard when
 * SellEvaluator processes sells against a newer session.
 */
class NexusSessionCheck extends Command
{
    protected $signature = 'nexus:session-check';
    protected $description = 'NEXUS: Open or close trading sessions based on configured schedule';

    public function handle(): void
    {
        if (!NexusConfig::isNexusActive()) return;
        if (NexusConfig::isEmergencyPaused()) return;

        $controller = new SessionController();
        $controller->checkAndOpenSessions();
        $controller->checkAndCloseSessions();

        // Auto-complete orphaned sessions stuck in "processing" for over 2 hours.
        // This happens when SellEvaluator evaluates sells against a newer session,
        // leaving older sessions in "processing" forever.
        // Checks actual_end first; falls back to created_at for ghost sessions
        // that never had an actual_end set.
        NexusSession::where('status', 'processing')
            ->where(function ($q) {
                $q->where('actual_end', '<=', Carbon::now()->subHours(2))
                  ->orWhere(function ($q2) {
                      $q2->whereNull('actual_end')
                         ->where('created_at', '<=', Carbon::now()->subHours(2));
                  });
            })
            ->update(['status' => 'completed']);
    }
}