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

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 { userIds, tenantIds, confirmation } = await req.json();

    if (confirmation !== 'DELETE') {
      return NextResponse.json({ error: 'Invalid Confirmation Keyword' }, { status: 400 });
    }

    if (userIds && userIds.length > 0) {
      await writerDb.delete(users).where(inArray(users.id, userIds));
    }

    if (tenantIds && tenantIds.length > 0) {
      await writerDb.delete(users).where(inArray(users.tenantId, tenantIds));
      await writerDb.delete(tenants).where(inArray(tenants.id, tenantIds));
    }

    await writerDb.insert(quantumLogs).values({
      actor: decoded.email,
      action: 'MASS_BULK_KILL',
      targetId: `Users:${userIds?.length||0}, Tenants:${tenantIds?.length||0}`,
      ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
      userAgent: req.headers.get('user-agent') || 'Unknown'
    });

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