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

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

    const logs = await db.select().from(quantumLogs).orderBy(desc(quantumLogs.nanoTimestamp)).limit(100);
    return NextResponse.json({ logs });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}

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

    const body = await req.json();
    if (!body.ids || !Array.isArray(body.ids)) return NextResponse.json({ error: 'Bad Request' }, { status: 400 });

    await writerDb.delete(quantumLogs).where(inArray(quantumLogs.id, body.ids));

    return NextResponse.json({ success: true });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
