import { NextResponse } from 'next/server';
import { writerDb } from "@/drizzle/db";
import { 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 { tenantId, licenses, platformName, brandColor, allowCrossGroup } = await req.json();

    const updateData: Record<string, string | boolean> = {};
    if (licenses !== undefined) updateData.licenses = JSON.stringify(licenses);
    if (platformName !== undefined) updateData.platformName = platformName;
    if (brandColor !== undefined) updateData.brandColor = brandColor;
    if (allowCrossGroup !== undefined) updateData.allowCrossGroup = allowCrossGroup;

    await writerDb.update(tenants).set(updateData).where(eq(tenants.id, tenantId));
    
    await writerDb.insert(quantumLogs).values({
      actor: decoded.email,
      action: 'QUANTUM_MODIFIER_OVERRIDE',
      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 });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
