import { NextResponse } from 'next/server';
import { db, writerDb } from "@/drizzle/db";
import { users, tenants, messages, quantumLogs, saasPackages } from "@/drizzle/schema";
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import os from 'os';
import { eq, sql } from 'drizzle-orm';

export const dynamic = 'force-dynamic';

export async function GET(req: Request) {
  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 { email: string; role: string };
    
    if (decoded.role !== 'superadmin') {
      return NextResponse.json({ error: 'Access Denied: Supreme Mode Required' }, { status: 403 });
    }

    // 1. Server Health
    const serverVitals = {
      cpuCount: os.cpus().length,
      cpuModel: os.cpus()[0]?.model || 'Unknown',
      totalMemMB: Math.round(os.totalmem() / 1024 / 1024),
      freeMemMB: Math.round(os.freemem() / 1024 / 1024),
      uptimeSecs: Math.round(os.uptime())
    };

    // 2. Metrics
    // Using simple count logic by pulling array length or specific aggregations.
    // For pure Postgres counts, we can do direct selects.
    const allUsersCountResult = await db.execute(sql`SELECT count(*) FROM users`);
    const allTenantsCountResult = await db.execute(sql`SELECT count(*) FROM tenants`);
    const allMessagesCountResult = await db.execute(sql`SELECT count(*) FROM messages`);
    
    const totalUsers = parseInt(allUsersCountResult[0].count as string);
    const totalTenants = parseInt(allTenantsCountResult[0].count as string);
    const totalMessages = parseInt(allMessagesCountResult[0].count as string);

    // 3. Omni-Penetration Matrix (Limit top 50 tenants for dashboard performance)
    const allTenants = await db.select().from(tenants).limit(50);
    const tenantIds = allTenants.map(t => t.id);
    const allPackages = await db.select().from(saasPackages);
    
    // We fetch users for each displayed tenant to show in Supreme Admin
    const allUsers = await db.select({
      id: users.id,
      email: users.email,
      role: users.role,
      tenantId: users.tenantId,
    }).from(users);
    
    const matrix = allTenants.map(tenant => {
      const tenantPackage = allPackages.find(p => p.id === tenant.packageId) || null;
      const tenantUsers = allUsers.filter(u => u.tenantId === tenant.id);
      return {
        ...tenant,
        package: tenantPackage,
        users: tenantUsers
      };
    });

    // 4. Record the quantum log (wrap in try-catch for read-replicas)
    try {
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'OMNI_SIGHT_ACCESS',
        targetId: 'ALL_SYSTEMS',
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
    } catch (logError) {
      console.warn('[SUPREME EYE] Could not insert quantum log (likely read replica):', logError);
    }

    return NextResponse.json({
      serverVitals,
      metrics: {
        totalUsers: totalUsers,
        totalTenants: totalTenants,
        totalMessages: totalMessages
      },
      matrix
    });

  } catch (error: unknown) {
    console.error('[SUPREME EYE ERROR]', error);
    return NextResponse.json({ error: 'Internal System Error' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  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 { email: string; role: string };
    if (decoded.role !== 'superadmin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    const body = await req.json();
    const { action, tenantId, licenses, byokEnabled, byokKey } = body;

    if (action === 'update_tenant_licenses') {
      const updateData: { licenses: string; byokEnabled?: boolean; byokKey?: string } = {
        licenses: JSON.stringify(licenses)
      };
      
      if (typeof byokEnabled === 'boolean') updateData.byokEnabled = byokEnabled;
      if (typeof byokKey === 'string') updateData.byokKey = byokKey;

      await writerDb.update(tenants).set(updateData).where(eq(tenants.id, tenantId));

      try {
        await writerDb.insert(quantumLogs).values({
          actor: decoded.email,
          action: 'SUPREME_MATRIX_UPDATE',
          targetId: tenantId,
          ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
          userAgent: req.headers.get('user-agent') || 'Unknown'
        });
      } catch (logError) {
        console.warn('[SUPREME EYE] Could not insert quantum log (likely read replica):', logError);
      }

      return NextResponse.json({ success: true });
    }

    if (action === 'update_tenant_package') {
      const { packageId } = body;
      await writerDb.update(tenants).set({ packageId: packageId || null }).where(eq(tenants.id, tenantId));
      try {
        await writerDb.insert(quantumLogs).values({
          actor: decoded.email,
          action: 'SUPREME_PACKAGE_ASSIGN',
          targetId: tenantId,
          ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
          userAgent: req.headers.get('user-agent') || 'Unknown'
        });
      } catch (logError) {
        console.warn('[SUPREME EYE] Could not insert quantum log (likely read replica):', logError);
      }
      return NextResponse.json({ success: true });
    }

    if (action === 'update_security_tier') {
      const { securityTier } = body;
      if (!['STANDARD', 'SOVEREIGN', 'CLIENT_CA'].includes(securityTier)) {
        return NextResponse.json({ error: 'Invalid security tier' }, { status: 400 });
      }
      await writerDb.update(tenants).set({ securityTier }).where(eq(tenants.id, tenantId));
      try {
        await writerDb.insert(quantumLogs).values({
          actor: decoded.email,
          action: `SECURITY_TIER_SWITCH_${securityTier}`,
          targetId: tenantId,
          ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
          userAgent: req.headers.get('user-agent') || 'Unknown'
        });
      } catch (logError) {
        console.warn('[SUPREME EYE] Could not insert quantum log:', logError);
      }
      return NextResponse.json({ success: true });
    }

    return NextResponse.json({ error: 'Invalid Action' }, { status: 400 });

  } catch (error: any) {
    console.error('[SUPREME EYE POST ERROR]', error);
    return NextResponse.json({ error: error.message || 'Internal System Error' }, { status: 500 });
  }
}
