import { API_ENDPOINTS } from "./endpoints";

const TEST_API_BASE_URL = "https://admin.opplenz.com/admin/v1";
const PRODUCTION_API_BASE_URL = "https://admin.opplens.com/admin/v1";

/**
 * Absolute base URL of the backend admin API for the current deploy.
 *
 * Mirrors the host-based proxy in `next.config.mjs`:
 *   - production (`opplens.com`)  -> admin.opplens.com/admin/v1
 *   - test (`opplenz.com`) + dev  -> admin.opplenz.com/admin/v1
 *
 * Axios calls use the relative `/api/proxy/` base (so the browser attaches auth
 * headers same-origin and the rewrite picks the right backend), but values that
 * get persisted on the backend (e.g. a `profile_image` download URL) must be
 * absolute and domain-correct. Resolved at call time because the host is only
 * known in the browser.
 */
export const getBackendApiBaseUrl = (): string => {
  const override = process.env.NEXT_PUBLIC_BACKEND_API_BASE_URL;
  if (override) return override;

  if (
    typeof window !== "undefined" &&
    /(^|\.)opplens\.com$/.test(window.location.hostname)
  ) {
    return PRODUCTION_API_BASE_URL;
  }

  return TEST_API_BASE_URL;
};

/** Absolute, directly-loadable URL for a stored GridFS file. */
export const buildFileDownloadUrl = (fileId: string) =>
  `${getBackendApiBaseUrl()}/${API_ENDPOINTS.FILES.DOWNLOAD(fileId)}`;

/** Pull the GridFS file id out of a stored download URL, if it is one. */
export const extractFileId = (url: string): string | undefined =>
  url.match(/\/files\/([^/]+)\/download/)?.[1];
