import { parseAgentEnv } from "@code/env/agent";
import type { AgentRouteHandler } from "@flue/runtime";

/** Only Convex may invoke or observe the organization-scoped Flue agent. */
export const convexAgentRoute: AgentRouteHandler = async (context, next) => {
  const env = parseAgentEnv(process.env);
  const authorization = context.req.header("authorization");
  if (authorization !== `Bearer ${env.FLUE_DB_TOKEN}`) {
    return context.json({ error: "Unauthorized" }, 401);
  }

  const organizationId = context.req.header("x-zopu-organization-id");
  if (!organizationId || organizationId !== context.req.param("id")) {
    return context.json({ error: "Forbidden" }, 403);
  }

  return await next().then(() => context.res);
};
