<?php

namespace App\Nexus\Console\Commands;

use App\Nexus\Engine\EconomyGuardian;
use App\Nexus\Models\NexusEconomySnapshot;
use App\Models\Sell;
use App\Models\Investment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * Captures daily economy health metrics to nexus_economy_snapshots.
 * Runs daily at 00:05 UTC via Laravel scheduler.
 *
 * Runs regardless of nexus_status -- we want baseline economy data
 * even during the build phase so we have historical context at go-live.
 *
 * The deployed snapshot table is session-oriented (nexus_session_id,
 * snapshot_type). Daily snapshots use snapshot_type = 'daily' with
 * no session ID. Full economy health stored in market_breakdown JSON.
 */
class NexusEconomySnapshotCommand extends Command
{
    protected $signature = 'nexus:economy-snapshot';
    protected $description = 'NEXUS: Capture daily economy health snapshot';

    public function handle(): void
    {
        // No kill switch check -- snapshots run during build for baseline data

        $guardian = new EconomyGuardian();
        $health = $guardian->getEconomyHealth();

        // Calculate values for the deployed table columns
        $totalPendingSellValue = Sell::where('type', 'manual_sell')
            ->where('status', 0)
            ->sum(\DB::raw('amount * quantity'));

        $totalActiveInvestment = Investment::where('status', 2)
            ->where('funded', 1)
            ->sum('amount');

        NexusEconomySnapshot::create([
            'nexus_session_id'         => null, // Daily snapshot, not session-specific
            'snapshot_type'            => 'daily',
            'total_pending_sell_value' => $totalPendingSellValue,
            'total_active_investment'  => $totalActiveInvestment,
            'platform_liquidity'       => $health['liquidity_index'] * 100, // Store as percentage
            'recess_threshold'         => null,
            'excess_threshold'         => null,
            'market_breakdown'         => $health, // Full economy health stored as JSON
            'captured_at'              => now(),
        ]);

        $this->info("Economy snapshot captured: {$health['economy_health']} (liquidity: {$health['liquidity_index']})");
        Log::info('[NEXUS] economy-snapshot captured', $health);
    }
}
