import createClient from "openapi-fetch";

import { config } from "@config/config";
import type { paths as AgentPaths } from "@/generated/agentApi";
import type { paths as ServerPaths } from "@/generated/serverApi";
import { applyAuthContextHeaders } from "@/lib/requestHeaders";

const authMiddleware = {
  async onRequest({ request }: { request: Request }) {
    const headers = new Headers(request.headers);
    await applyAuthContextHeaders(request.url, headers);
    return new Request(request, { headers });
  },
};

export const serverApi = createClient<ServerPaths>({
  baseUrl: config.BACKEND_URL,
});
export const agentApi = createClient<AgentPaths>({
  baseUrl: config.AGENT_URL,
});

serverApi.use(authMiddleware);
agentApi.use(authMiddleware);
