/**
 * Host routing for store landing pages.
 *
 * A seller points `shop.example.com` at Alqove; these helpers map an inbound
 * Host header to their store slug so the proxy can rewrite the request into the
 * `/s/{slug}` route group. The visitor's URL never changes — they stay on their
 * own domain — while Next renders the same pages the canonical
 * `alqove.com/s/{slug}` path serves.
 */

const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";

/** Hosts Alqove serves itself; everything else is a candidate custom domain. */
export const PLATFORM_HOSTS = (
  process.env.NEXT_PUBLIC_PLATFORM_HOSTS || "alqove.com,localhost,127.0.0.1"
)
  .split(",")
  .map((h) => h.trim().toLowerCase())
  .filter(Boolean);

/** How long a resolution — hit or miss — is trusted, in ms. */
export const RESOLUTION_TTL_MS = 60_000;

interface CacheEntry {
  slug: string | null;
  expiresAt: number;
}

// Module scope survives between invocations on a warm instance. Misses are
// cached too, so an unknown host costs one API call a minute, not one per
// request.
const cache = new Map<string, CacheEntry>();

/** Test seam — the cache would otherwise leak between cases. */
export function clearStorefrontHostCache(): void {
  cache.clear();
}

/** Strip the port: `localhost:3000` and `localhost` are the same host to us. */
export function normalizeHost(raw: string | null | undefined): string | null {
  if (!raw) return null;
  const host = raw.split(",")[0].trim().toLowerCase().split(":")[0];
  return host || null;
}

export function isPlatformHost(host: string): boolean {
  return PLATFORM_HOSTS.some((base) => host === base || host.endsWith(`.${base}`));
}

/** True once a path is already inside the storefront group — never re-prefix. */
export function isStorefrontPath(pathname: string): boolean {
  return pathname === "/s" || pathname.startsWith("/s/");
}

export function storefrontPathFor(slug: string, pathname: string): string {
  return `/s/${slug}${pathname === "/" ? "" : pathname}`;
}

export async function resolveStorefrontSlug(host: string): Promise<string | null> {
  const cached = cache.get(host);
  if (cached && cached.expiresAt > Date.now()) {
    return cached.slug;
  }

  let slug: string | null = null;

  try {
    const res = await fetch(
      `${API_URL}/v1/storefronts/resolve?hostname=${encodeURIComponent(host)}`,
      { headers: { Accept: "application/json" } },
    );

    if (res.ok) {
      const body = (await res.json()) as { data?: { store_slug?: string } };
      slug = body.data?.store_slug ?? null;
    }
  } catch {
    // API unreachable — treat as unresolved rather than 500ing every request on
    // this host. The negative cache keeps the retry rate sane.
    slug = null;
  }

  cache.set(host, { slug, expiresAt: Date.now() + RESOLUTION_TTL_MS });

  return slug;
}
