<?php

namespace App\Nexus\Console\Commands;

use App\Nexus\Models\NexusSession;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

/**
 * Removes old records to keep the database lean.
 * Runs daily at 03:00 UTC via Laravel scheduler.
 *
 * Cleanup targets:
 *   - nexus_audit_log entries older than 90 days
 *   - nexus_economy_snapshots entries older than 365 days
 *   - nexus_sessions with status 'completed' older than 30 days
 *
 * Runs regardless of nexus_status -- housekeeping is always needed.
 */
class NexusCleanup extends Command
{
    protected $signature = 'nexus:cleanup';
    protected $description = 'NEXUS: Remove old audit log, snapshot, and session records';

    public function handle(): void
    {
        $totalDeleted = 0;

        // Audit log: older than 90 days
        $auditCutoff = Carbon::now()->subDays(90);
        $auditDeleted = DB::table('nexus_audit_log')
            ->where('created_at', '<', $auditCutoff)
            ->delete();
        $totalDeleted += $auditDeleted;

        // Economy snapshots: older than 365 days
        $snapshotCutoff = Carbon::now()->subDays(365);
        $snapshotDeleted = DB::table('nexus_economy_snapshots')
            ->where('captured_at', '<', $snapshotCutoff)
            ->delete();
        $totalDeleted += $snapshotDeleted;

        // Completed sessions: older than 30 days
        $sessionCutoff = Carbon::now()->subDays(30);
        $sessionDeleted = NexusSession::where('status', NexusSession::STATUS_COMPLETED)
            ->where('updated_at', '<', $sessionCutoff)
            ->delete();
        $totalDeleted += $sessionDeleted;

        if ($totalDeleted > 0) {
            $this->info("Cleaned: {$auditDeleted} audit logs, {$snapshotDeleted} snapshots, {$sessionDeleted} sessions");
            Log::info('[NEXUS] cleanup complete', [
                'audit_deleted'    => $auditDeleted,
                'snapshot_deleted' => $snapshotDeleted,
                'session_deleted'  => $sessionDeleted,
            ]);
        }
    }
}
