import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import {
  getRoleById,
  updateRole,
  deleteRole,
  getRolePermissions,
  setRolePermissions,
} from "@/lib/rbac";
import { createAuditLog } from "@/lib/log";

function getAuthInfo(req: NextRequest) {
  return {
    userId: parseInt(req.headers.get("x-admin-user-id") || "0", 10),
    username: req.headers.get("x-admin-username") || "unknown",
  };
}

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const roleId = parseInt(id, 10);
    const role = await getRoleById(roleId);
    if (!role) return NextResponse.json({ error: "角色不存在" }, { status: 404 });
    const permissions = await getRolePermissions(roleId);
    return NextResponse.json({ ...role, permissions });
  } catch (e) {
    logError("Get role error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const roleId = parseInt(id, 10);
    const body = await req.json() as {
      name?: string;
      description?: string;
      permissionIds?: number[];
    };

    const role = await updateRole(roleId, body.name || "", body.description);
    if (!role) return NextResponse.json({ error: "角色不存在" }, { status: 404 });

    if (body.permissionIds !== undefined) {
      await setRolePermissions(roleId, body.permissionIds);
    }

    const { userId, username } = getAuthInfo(req);
    await createAuditLog({
      userId,
      username,
      action: "update",
      resource: "admin_role",
      resourceId: id,
      requestParams: body,
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json(role);
  } catch (e) {
    logError("Update role error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const roleId = parseInt(id, 10);
    const ok = await deleteRole(roleId);
    if (!ok) return NextResponse.json({ error: "角色不存在" }, { status: 404 });

    const { userId, username } = getAuthInfo(req);
    await createAuditLog({
      userId,
      username,
      action: "delete",
      resource: "admin_role",
      resourceId: id,
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ success: true });
  } catch (e) {
    logError("Delete role error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
