import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import {
  listRoles,
  createRole,
  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() {
  try {
    const roles = await listRoles();
    return NextResponse.json({ roles });
  } catch (e) {
    logError("List roles error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json() as {
      name?: string;
      description?: string;
      permissionIds?: number[];
    };
    const { name = "", description = "" } = body;

    if (!name) {
      return NextResponse.json({ error: "角色名称不能为空" }, { status: 400 });
    }

    const role = await createRole(name, description);

    if (body.permissionIds?.length) {
      await setRolePermissions(role.id, body.permissionIds);
    }

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

    return NextResponse.json(role, { status: 201 });
  } catch (e: unknown) {
    if ((e as { code?: string }).code === "23505") {
      return NextResponse.json({ error: "角色名已存在" }, { status: 409 });
    }
    logError("Create role error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
