import { getAccessToken } from "@/lib/authToken";
import { useProjectStore } from "@/store/projectStore";

export type AuthHeaderMode = "include" | "omit";
export type ProjectHeaderMode = "auto" | "include" | "omit";

export interface AuthContextHeaderOptions {
  authHeaderMode?: AuthHeaderMode;
  projectHeaderMode?: ProjectHeaderMode;
}

const shouldIncludeProjectHeader = (
  url: string,
  projectHeaderMode: ProjectHeaderMode,
) => {
  if (projectHeaderMode === "include") {
    return true;
  }

  if (projectHeaderMode === "omit") {
    return false;
  }

  const pathname = new URL(url, "http://tjwater.local").pathname.replace(/\/+$/, "");
  return pathname !== "/api/v1/projects";
};

export const applyAuthContextHeaders = async (
  url: string,
  headers: Headers,
  options: AuthContextHeaderOptions = {},
) => {
  const accessToken = await getAccessToken();
  if (accessToken && options.authHeaderMode !== "omit") {
    headers.set("Authorization", `Bearer ${accessToken}`);
  }

  const projectId = useProjectStore.getState().currentProjectId;
  if (
    projectId &&
    shouldIncludeProjectHeader(url, options.projectHeaderMode ?? "auto")
  ) {
    headers.set("X-Project-Id", projectId);
  }

  return headers;
};
