import type { Permission } from "@/lib/constants/auth";
import { ADMIN_ROLE } from "@/lib/constants/auth";
import { forbidden } from "@/modules/auth/errors";
import type { AuthContext } from "@/modules/auth/rbac";

export type AdminAuthContext = Extract<AuthContext, { type: "admin" }>;

/** 从 middleware 注入的请求头解析管理员鉴权上下文 */
export function parseAdminAuth(request: Request): AdminAuthContext {
  const authType = request.headers.get("x-auth-type");
  if (authType !== "admin") {
    throw forbidden("需要管理员权限");
  }

  const userId = request.headers.get("x-user-id");
  const role = request.headers.get("x-user-role");

  if (!userId || role !== ADMIN_ROLE) {
    throw forbidden("需要管理员权限");
  }

  return {
    type: "admin",
    userId,
    role: ADMIN_ROLE,
  };
}

export type { Permission };
