import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { isCheckinHost, isPathAllowedOnCheckinHost } from "@/lib/checkin/host";
import {
  isPlatformHost,
  isStorefrontPath,
  normalizeHost,
  resolveStorefrontSlug,
  storefrontPathFor,
} from "@/lib/storefront/host";

/**
 * Host-based routing for the two lanes that live on their own domains.
 *
 * 1. Check-in subdomain — on `checkin.alqove.com` only the public `/c/...` lane
 *    is served; anything else 404s so the main marketplace (and its cookies)
 *    never surface there. DNS/deploy: point `checkin.alqove.com` at the same
 *    deployment behind Cloudflare (WAF + Turnstile). No separate build — the
 *    route group is shared.
 *
 * 2. Store custom domains — a seller's own hostname is resolved to their store
 *    slug and rewritten into the `/s/{slug}` route group, so their landing page
 *    is served from their domain with their URLs intact.
 *
 * Alqove's own hosts are left alone, so `/c/{token}` and `/s/{slug}` both work
 * in dev without any DNS setup.
 *
 * Uses the `proxy` file convention (Next 16 renamed `middleware` → `proxy`).
 */
export async function proxy(req: NextRequest) {
  const rawHost = req.headers.get("host");

  if (isCheckinHost(rawHost) && !isPathAllowedOnCheckinHost(req.nextUrl.pathname)) {
    return new NextResponse("Not found", { status: 404 });
  }

  const host = normalizeHost(rawHost);

  // Platform hosts (and anything already inside the storefront group) need no
  // lookup — this keeps the API call off every marketplace request.
  if (!host || isPlatformHost(host) || isStorefrontPath(req.nextUrl.pathname)) {
    return NextResponse.next();
  }

  const slug = await resolveStorefrontSlug(host);

  if (!slug) {
    return NextResponse.next();
  }

  const url = req.nextUrl.clone();
  url.pathname = storefrontPathFor(slug, url.pathname);

  return NextResponse.rewrite(url);
}

export const config = {
  // Skip Next internals + static assets.
  matcher: ["/((?!_next/|favicon.ico|.*\\.[\\w]+$).*)"],
};
