function normalizeBaseUrl(value: string | undefined) {
  const normalized = (value ?? "").trim();

  if (!normalized) {
    return "";
  }

  return normalized.replace(/\/+$/, "");
}

export const storefrontConfig = {
  wordpressBaseUrl: normalizeBaseUrl(process.env.WORDPRESS_BASE_URL),
};

export function getWordPressBaseUrl() {
  if (!storefrontConfig.wordpressBaseUrl) {
    throw new Error(
      "Missing WORDPRESS_BASE_URL. Add it to .env.local before using the starter.",
    );
  }

  return storefrontConfig.wordpressBaseUrl;
}

export function getWordPressApiUrl(path: string) {
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;

  return `${getWordPressBaseUrl()}${normalizedPath}`;
}

export function getWordPressRestApiUrl(path = "") {
  const normalizedPath = path
    ? path.startsWith("/") ? path : `/${path}`
    : "";

  return getWordPressApiUrl(`/wp-json${normalizedPath}`);
}

export function getWooStoreApiUrl(path = "") {
  const normalizedPath = path
    ? path.startsWith("/") ? path : `/${path}`
    : "";

  return getWordPressApiUrl(`/wp-json/wc/store/v1${normalizedPath}`);
}

export function getStorefrontRouteUrl(path: string) {
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;

  return getWordPressApiUrl(`/wp-json/storefront/v1${normalizedPath}`);
}
