import { headers } from "next/headers";
import { cache } from "react";
import { api } from "@/lib/api";
import type { StorefrontRenderContext } from "@/components/storefront/links";
import type { StorefrontPageResponse, StorefrontShell } from "@alqove/api-client";

/**
 * `cache()` dedupes within a single render pass, so the layout and the page can
 * each ask for the shell and only one request goes out.
 */
export const getShell = cache(async (slug: string): Promise<StorefrontShell | null> => {
  try {
    const res = await api.storefront.getShell(slug);
    return res.data;
  } catch {
    return null;
  }
});

export const getPage = cache(
  async (slug: string, pageSlug: string): Promise<StorefrontPageResponse | null> => {
    try {
      return await api.storefront.getPage(slug, pageSlug);
    } catch {
      return null;
    }
  },
);

/** Hosts Alqove serves itself — mirrors the middleware's list. */
function platformHosts(): string[] {
  return (process.env.NEXT_PUBLIC_PLATFORM_HOSTS || "alqove.com,localhost,127.0.0.1")
    .split(",")
    .map((h) => h.trim().toLowerCase())
    .filter(Boolean);
}

/**
 * Storefront links have to work from two addresses at once: `/s/{slug}/about`
 * on an Alqove host, and `/about` on the seller's own domain — where the
 * middleware has already rewritten the request into this route group.
 */
export async function resolveBasePath(slug: string): Promise<string> {
  const host = (await headers()).get("host")?.split(":")[0]?.toLowerCase() ?? "";
  const onPlatform =
    host === "" || platformHosts().some((base) => host === base || host.endsWith(`.${base}`));

  return onPlatform ? `/s/${slug}` : "";
}

export async function buildContext(
  slug: string,
  shell: StorefrontShell,
): Promise<StorefrontRenderContext> {
  return { shell, slug, basePath: await resolveBasePath(slug) };
}
