import { GlobalFunctions } from "@/GlobalFunctions";

import { resolveCommanderUnidadeId } from "./unidadeContext";
import { resolveCommanderBaseUrl } from "./fechamentoBaseUrl";

export { resolveCommanderBaseUrl } from "./fechamentoBaseUrl";

export type BuildCommanderHeadersOptions = {
  /** Rotas allowlisted no Commander (ex.: `/me`, lookup de `/unidades`) não devem enviar `X-Unidade-Id`. */
  omitUnidadeId?: boolean;
};

export async function buildCommanderHeaders(
  opts?: BuildCommanderHeadersOptions,
): Promise<Record<string, string>> {
  const token = await GlobalFunctions.getToken();
  const apiKey = import.meta.env.VITE_API_KEY || "";
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...(apiKey ? { apikey: apiKey } : {}),
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
  if (!opts?.omitUnidadeId) {
    headers["X-Unidade-Id"] = await resolveCommanderUnidadeId();
  }
  return headers;
}
