import { buildApi } from "@xtablo/shared";
import { getStoredAdminSession } from "./adminSession";

const LOCAL_ADMIN_API_BASE_URL = "http://localhost:8080/api/v1";
const PRODUCTION_ADMIN_API_BASE_URL = "https://api.xtablo.com/api/v1";

export function resolveAdminApiBaseUrl(mode = import.meta.env.MODE, _envApiUrl?: string) {
  if (mode === "development") {
    return LOCAL_ADMIN_API_BASE_URL;
  }

  return PRODUCTION_ADMIN_API_BASE_URL;
}

const apiBaseUrl = resolveAdminApiBaseUrl();

export const adminApi = buildApi(apiBaseUrl);

adminApi.interceptors.request.use((config) => {
  const adminSession = getStoredAdminSession();

  if (adminSession) {
    config.headers.Authorization = `Bearer ${adminSession.sessionToken}`;
  }

  return config;
});
