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';
import bcrypt from 'bcryptjs';

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 { type, id, newValue, role, password, engineStrategy, chatEngineStrategy } = body;

    if (type === 'TENANT') {
      const updatePayload: Record<string, string> = { name: newValue };
      if (engineStrategy) updatePayload.mediaEngineStrategy = engineStrategy;
      if (chatEngineStrategy) updatePayload.chatEngineStrategy = chatEngineStrategy;
      await writerDb.update(tenants).set(updatePayload).where(eq(tenants.id, id));
    } else if (type === 'USER') {
      const updateData: Record<string, string> = { email: newValue };
      if (role) updateData.role = role;
      if (password && password.trim() !== '') {
        updateData.passwordHash = await bcrypt.hash(password, 12);
      }
      
      await writerDb.update(users).set(updateData).where(eq(users.id, id));
    } else {
      return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
    }

    await writerDb.insert(quantumLogs).values({
      actor: decoded.email,
      action: `MATRIX_INLINE_EDIT_${type}`,
      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 });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
