import { NextRequest, NextResponse } from "next/server";
import { requireMainAdmin, getClientMetadata } from "@/lib/admin/auth";
import { db } from "@/lib/admin/db";

export const dynamic = "force-dynamic";

/**
 * PATCH /api/admin/roles/[id]
 * Updates a custom role's name, description, or permissions.
 */
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const auth = await requireMainAdmin(req);
    const { id } = await params;
    const body = await req.json().catch(() => ({}));

    const role = await db.getRoleById(id);
    if (!role) {
      return NextResponse.json({ error: "Role not found." }, { status: 404 });
    }

    if (role.isSystem) {
      return NextResponse.json(
        { error: "Built-in system roles cannot be modified." },
        { status: 400 }
      );
    }

    const updates: Record<string, any> = {};
    if (typeof body.name === "string" && body.name.trim()) {
      if (/main.*admin/i.test(body.name)) {
        return NextResponse.json(
          { error: "Custom role name cannot mimic Main Admin." },
          { status: 400 }
        );
      }
      updates.name = body.name.trim();
    }
    if (typeof body.description === "string") {
      updates.description = body.description.trim();
    }
    if (Array.isArray(body.permissions)) {
      updates.permissions = body.permissions.filter((p: any) => typeof p === "string");
    }

    const updated = await db.updateRole(id, updates);

    const { ip } = getClientMetadata(req);
    await db.logSecurityEvent({
      actorId: auth.user.id,
      actorName: auth.user.name,
      actorEmail: auth.user.email,
      actorLevel: auth.user.level,
      targetUserId: null,
      targetUserEmail: null,
      targetUserName: null,
      action: "ROLE_CHANGED",
      details: { roleId: id, updates },
      ipAddress: ip,
    });

    return NextResponse.json({ role: updated });
  } catch (err: any) {
    console.error("[PATCH /api/admin/roles/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to update role." },
      { status: err.status || 500 }
    );
  }
}

/**
 * DELETE /api/admin/roles/[id]
 * Deletes a custom role (only if 0 administrators are currently assigned).
 */
export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const auth = await requireMainAdmin(req);
    const { id } = await params;

    const role = await db.getRoleById(id);
    if (!role) {
      return NextResponse.json({ error: "Role not found." }, { status: 404 });
    }

    if (role.isSystem) {
      return NextResponse.json(
        { error: "Built-in system roles cannot be deleted." },
        { status: 400 }
      );
    }

    await db.deleteRole(id);

    const { ip } = getClientMetadata(req);
    await db.logSecurityEvent({
      actorId: auth.user.id,
      actorName: auth.user.name,
      actorEmail: auth.user.email,
      actorLevel: auth.user.level,
      targetUserId: null,
      targetUserEmail: null,
      targetUserName: null,
      action: "ROLE_CHANGED",
      details: { action: "ROLE_DELETED", roleId: id, roleName: role.name },
      ipAddress: ip,
    });

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error("[DELETE /api/admin/roles/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to delete role." },
      { status: err.status || 400 }
    );
  }
}
