import { NextResponse } from 'next/server';
import { db } from "@/drizzle/db";
import { networkTelemetry, quantumLogs, liveKillSwitches } from "@/drizzle/schema";
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import { desc, count, sql } from 'drizzle-orm';

export const dynamic = 'force-dynamic';

interface DecodedToken {
  userId: string;
  email: string;
  role: string;
  tenantId: string;
}

// PANOPTICON: Supreme Admin Telemetry API (Global View)
// Returns real data from network_telemetry and quantum_logs tables.
export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;
    if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as DecodedToken;
    if (decoded.role !== 'superadmin') {
      return NextResponse.json({ error: 'Akses Absolut Diperlukan' }, { status: 403 });
    }

    // 1. Recent telemetry entries (last 50)
    const recentTelemetry = await db.select().from(networkTelemetry)
      .orderBy(desc(networkTelemetry.timestamp))
      .limit(50);

    // 2. Recent quantum logs (last 100)
    const recentLogs = await db.select().from(quantumLogs)
      .orderBy(desc(quantumLogs.nanoTimestamp))
      .limit(100);

    // 3. Active kill switches
    const activeKills = await db.select().from(liveKillSwitches);

    // 4. Aggregated stats
    const [telemetryCount] = await db.select({ total: count() }).from(networkTelemetry);
    const [logsCount] = await db.select({ total: count() }).from(quantumLogs);
    const [killsCount] = await db.select({ total: count() }).from(liveKillSwitches);

    // 5. Bandwidth aggregate (sum of traffic bytes from last 24h)
    const bandwidthAgg = await db.select({
      totalBytes: sql<string>`COALESCE(SUM(CAST(traffic_bytes AS BIGINT)), 0)`,
      avgResponseMs: sql<string>`COALESCE(AVG(CAST(response_time_ms AS NUMERIC)), 0)`,
    }).from(networkTelemetry);

    return NextResponse.json({
      telemetry: recentTelemetry,
      logs: recentLogs,
      kills: activeKills,
      stats: {
        totalTelemetryRecords: telemetryCount?.total || 0,
        totalLogRecords: logsCount?.total || 0,
        activeKillSwitches: killsCount?.total || 0,
        totalBandwidthBytes: bandwidthAgg[0]?.totalBytes || '0',
        avgResponseTimeMs: parseFloat(String(bandwidthAgg[0]?.avgResponseMs || '0')).toFixed(2),
      },
    });
  } catch (error: unknown) {
    console.error('[SUPREME TELEMETRY ERROR]', error);
    return NextResponse.json({ error: 'Telemetry Sync Failed' }, { status: 500 });
  }
}
