import { NextResponse } from "next/server";

const PUBLIC_MCP_BETA_TOKEN = (process.env.PUBLIC_MCP_BETA_TOKEN || "").trim();

export function isA2aRequestAuthorized(request: Request) {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    return false;
  }

  const token = authHeader.slice("Bearer ".length);
  return Boolean(process.env.API_KEY && token === process.env.API_KEY) ||
    Boolean(PUBLIC_MCP_BETA_TOKEN && token === PUBLIC_MCP_BETA_TOKEN);
}

export function a2aUnauthorizedResponse(id: string | number | null = null) {
  return NextResponse.json({
    jsonrpc: "2.0",
    error: { code: -32001, message: "Unauthorized" },
    id,
  }, { status: 401 });
}
