import { NextResponse } from 'next/server';
import { writerDb } from "@/drizzle/db";
import { users, tenants, quantumLogs } from "@/drizzle/schema";
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, tenantName, userEmail, userPassword, userRole, tenantId } = body;

    if (type === 'TENANT') {
      if (!tenantName) return NextResponse.json({ error: 'Tenant Name required' }, { status: 400 });
      await writerDb.insert(tenants).values({
        name: tenantName,
        isActive: true
      });
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'MATRIX_ADD_TENANT',
        targetId: tenantName,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
    } else if (type === 'USER') {
      if (!userEmail || !userPassword || !tenantId) {
        return NextResponse.json({ error: 'Email, Password, and Tenant ID are required' }, { status: 400 });
      }
      const hashedPassword = await bcrypt.hash(userPassword, 12);
      await writerDb.insert(users).values({
        email: userEmail,
        passwordHash: hashedPassword,
        tenantId: tenantId,
        role: userRole || 'user'
      });
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'MATRIX_ADD_USER',
        targetId: userEmail,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
    } else {
      return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
    }

    return NextResponse.json({ success: true });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
