import type { StorefrontShell } from "@alqove/api-client";

/**
 * Everything a block needs that isn't its own `data`. Passed down as props
 * rather than React context because storefront blocks render on the server.
 */
export interface StorefrontRenderContext {
  shell: StorefrontShell;
  slug: string;
  /**
   * Prefix for links that stay inside the storefront: `/s/{slug}` when served
   * from an Alqove host, and `''` when the visitor is on the seller's own
   * domain (where the middleware already maps `/` to this store).
   */
  basePath: string;
}

/**
 * A storefront can be served from the seller's own domain, where a relative
 * marketplace path (`/items/…`, `/stores/…`) would be rewritten back into the
 * storefront. Anything that leaves the storefront must therefore be absolute,
 * anchored on the canonical Alqove origin.
 */
export function marketplaceUrl(shell: StorefrontShell, path: string): string {
  const fallback = process.env.NEXT_PUBLIC_SITE_URL ?? "https://alqove.com";

  let origin = fallback;
  try {
    origin = new URL(shell.canonical_url ?? fallback).origin;
  } catch {
    // canonical_url misconfigured — the fallback origin is still correct.
  }

  return `${origin.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
}

/** Link to another page of this storefront. */
export function pagePath(ctx: StorefrontRenderContext, pageSlug: string): string {
  if (pageSlug === "home") return ctx.basePath || "/";
  return `${ctx.basePath}/${pageSlug}`;
}

/**
 * Seller-authored hrefs are written as if the storefront were the site root
 * (`/about`, `#products`), which is true on a custom domain but not under
 * `/s/{slug}`. Root-relative hrefs are rebased; anchors and absolute URLs pass
 * through untouched.
 */
export function resolveAuthoredHref(
  href: string | null,
  ctx: StorefrontRenderContext,
): string | null {
  if (!href) return null;
  if (!href.startsWith("/")) return href;
  return `${ctx.basePath}${href}` || "/";
}
