import { NextResponse } from 'next/server';
import { db, writerDb } from "@/drizzle/db";
import { users, tenants, messages, quantumLogs } from "@/drizzle/schema";
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import os from 'os';
import { eq } 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 (READ — menggunakan db)
    const allUsers = await db.select().from(users);
    const allTenants = await db.select().from(tenants);
    const allMessages = await db.select().from(messages);

    // 3. Omni-Penetration Matrix (Tenants + their users)
    const matrix = allTenants.map(tenant => {
      const tenantUsers = allUsers.filter(u => u.tenantId === tenant.id);
      return {
        ...tenant,
        users: tenantUsers
      };
    });

    // 4. Record the quantum log (WRITE — WAJIB writerDb)
    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'
    });

    return NextResponse.json({
      serverVitals,
      metrics: {
        totalUsers: allUsers.length,
        totalTenants: allTenants.length,
        totalMessages: allMessages.length
      },
      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;

      // FIXED: Static import (not dynamic), writerDb (not db)
      await writerDb.update(tenants).set(updateData).where(eq(tenants.id, tenantId));

      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'
      });

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

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

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