import { NextResponse } from 'next/server';
import { db, 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 body = await req.json();
    const { action, userId, targetTenantId, newRole, newTenantName } = body;

    const userRecord = await db.select().from(users).where(eq(users.id, userId));
    if (!userRecord.length) return NextResponse.json({ error: 'User not found' }, { status: 404 });

    if (action === 'TRANSFER') {
      await writerDb.update(users)
        .set({ tenantId: targetTenantId, role: newRole })
        .where(eq(users.id, userId));

      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'CROSS_USER_TRANSFER',
        targetId: userId,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });

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

    if (action === 'PROMOTE') {
      const [newTenant] = await writerDb.insert(tenants).values({
        name: newTenantName,
        isActive: true,
      }).returning();

      await writerDb.update(users)
        .set({ tenantId: newTenant.id, role: 'admin' })
        .where(eq(users.id, userId));

      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'CROSS_USER_PROMOTE',
        targetId: userId,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });

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

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