const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? process.env.API_BASE_URL ?? "";

function getApiOrigin() {
  try {
    return new URL(API_BASE_URL).origin;
  } catch {
    return "";
  }
}

export function resolveMediaUrl(value?: string | null) {
  const url = value?.trim() ?? "";

  if (!url) {
    return "";
  }

  if (
    /^[a-z][a-z0-9+.-]*:\/\//i.test(url) ||
    url.startsWith("//") ||
    url.startsWith("data:") ||
    url.startsWith("blob:")
  ) {
    return url;
  }

  const origin = getApiOrigin();
  if (!origin) {
    return url;
  }

  if (url.startsWith("/")) {
    return `${origin}${url}`;
  }

  return `${origin}/${url.replace(/^\/+/, "")}`;
}
