export type PublicCatalogProfile = {
  slug?: string | null;
  custom_domain?: string | null;
  custom_domain_verified?: boolean | null;
};

export function normalizePublicBaseUrl(origin: string) {
  const resolved = process.env.NEXT_PUBLIC_PUBLIC_CATALOG_BASE_URL || origin;
  const normalized = resolved.replace(":3002", ":3001").replace(/\/\/admin\./, "//");
  return normalized.replace(/\/$/, "");
}

export function normalizeCustomDomain(domain: string | null | undefined) {
  const raw = String(domain || "").trim().toLowerCase();
  if (!raw) return "";
  return raw.replace(/^https?:\/\//, "").split("/")[0]?.split(":")[0] || "";
}

export function getPublicCatalogOrigin(origin: string, profile: PublicCatalogProfile | null | undefined) {
  const customDomain = normalizeCustomDomain(profile?.custom_domain);
  if (customDomain && profile?.custom_domain_verified) {
    return `https://${customDomain}`;
  }
  return normalizePublicBaseUrl(origin);
}

export function buildPublicCatalogUrl(
  origin: string,
  profile: PublicCatalogProfile | null | undefined,
  options: { slugPath: string; customPath: string }
) {
  const base = getPublicCatalogOrigin(origin, profile);
  if (profile?.custom_domain_verified && normalizeCustomDomain(profile.custom_domain)) {
    return `${base}${options.customPath}`;
  }
  return `${base}${options.slugPath}`;
}
