import { headers } from "next/headers";
import { redirect } from "next/navigation";

import { CustomerLoginScreen } from "@/app/customer/_components/customer-login-screen";
import {
  defaultCustomerTenant,
  isPlatformApexHost,
  resolveCustomerTenantSlug,
  resolveHostnameFromHeaders,
  resolveTenantFromHost,
} from "@/lib/tenant";

type PageProps = {
  searchParams: Promise<{ redirect?: string }>;
};

/**
 * Host-style `/customer/login` on corporate subdomains.
 * Never redirect this page to `/login` or `/dashboard` on tenant hosts — that causes loops
 * when the proxy maps those paths back to `/customer/*`.
 */
export default async function CustomerLoginPage({ searchParams }: PageProps) {
  const headersList = await headers();
  const hostname = resolveHostnameFromHeaders(headersList);
  await searchParams; // reserve for future redirect passthrough
  const hostTenant = resolveTenantFromHost(hostname);

  if (isPlatformApexHost(hostname) && !hostTenant) {
    redirect("/login");
  }

  const tenant =
    resolveCustomerTenantSlug("/customer/login", hostname) ?? hostTenant ?? defaultCustomerTenant();

  return <CustomerLoginScreen tenant={tenant} />;
}
