/**
 * RBAC 中间件
 * Next.js middleware - 保护所有 /api/* 路由（认证路由除外）
 */
import { NextRequest, NextResponse } from "next/server";
import { parseSessionCookie, loadAdminSession, canAccess } from "@/lib/auth";

// 不需要认证的路由
const PUBLIC_PATHS = [
  "/api/auth/login",
  "/api/auth/oidc/authorize",
  "/api/auth/oidc/callback",
];

export async function middleware(req: NextRequest) {
  const path = req.nextUrl.pathname;

  // 公开路由放行
  if (PUBLIC_PATHS.some((p) => path.startsWith(p))) {
    return NextResponse.next();
  }

  // API 路由需要认证
  if (path.startsWith("/api/")) {
    const cookieHeader = req.headers.get("cookie");
    const sessionId = parseSessionCookie(cookieHeader);

    if (!sessionId) {
      return NextResponse.json({ error: "未登录" }, { status: 401 });
    }

    const session = await loadAdminSession(sessionId);
    if (!session) {
      return NextResponse.json({ error: "会话已过期" }, { status: 401 });
    }

    // 检查权限
    const requiredPermission = getRequiredPermission(path, req.method);
    if (requiredPermission && !canAccess(session, requiredPermission)) {
      return NextResponse.json({ error: "权限不足" }, { status: 403 });
    }

    // 将 session 信息注入到 headers 中传递给 API route
    const requestHeaders = new Headers(req.headers);
    requestHeaders.set("x-admin-user-id", String(session.userId));
    requestHeaders.set("x-admin-username", session.username);
    requestHeaders.set("x-admin-permissions", session.permissions.join(","));

    return NextResponse.next({ request: { headers: requestHeaders } });
  }

  return NextResponse.next();
}

function getRequiredPermission(path: string, method: string): string | null {
  // 用户管理
  if (path.startsWith("/api/users")) {
    if (method === "GET") return "user:read";
    if (method === "POST") return "user:create";
    if (method === "PUT" || method === "PATCH") return "user:update";
    if (method === "DELETE") return "user:delete";
  }

  // 角色管理
  if (path.startsWith("/api/roles")) {
    if (method === "GET") return "role:read";
    if (method === "POST") return "role:create";
    if (method === "PUT" || method === "PATCH") return "role:update";
    if (method === "DELETE") return "role:delete";
  }

  // 权限管理
  if (path.startsWith("/api/permissions")) {
    if (method === "GET") return "permission:read";
    if (method === "POST") return "permission:create";
    if (method === "PUT" || method === "PATCH") return "permission:update";
    if (method === "DELETE") return "permission:delete";
  }

  // 审计日志
  if (path.startsWith("/api/logs")) {
    if (method === "GET") return "log:read";
  }

  // 在线用户管理
  if (path.startsWith("/api/sessions")) {
    if (method === "GET") return "session:manage";
    if (method === "DELETE") return "session:manage";
  }

  return null;
}

export const config = {
  matcher: ["/api/:path*"],
};
