import { NextResponse } from 'next/server';
import { writerDb } from "@/drizzle/db";
import { users, tenants, quantumLogs } from "@/drizzle/schema";
import { eq } 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 { type, id, confirmation } = await req.json();

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

    if (type === 'USER') {
      await writerDb.delete(users).where(eq(users.id, id));
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'SURGICAL_KILL_USER',
        targetId: id,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
      return NextResponse.json({ success: true, message: 'User Terminated' });
    }

    if (type === 'TENANT') {
      await writerDb.delete(users).where(eq(users.tenantId, id));
      await writerDb.delete(tenants).where(eq(tenants.id, id));
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'MASS_KILL_TENANT',
        targetId: id,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
      return NextResponse.json({ success: true, message: 'Tenant and all its users Terminated' });
    }

    return NextResponse.json({ error: 'Invalid Type' }, { status: 400 });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
