import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { SitePage } from "@/app/(site)/_components/SitePage";
import { SiteHeader } from "@/app/(site)/_components/SiteHeader";
import { SiteFooter } from "@/app/(site)/_components/SiteFooter";
import { renderSections } from "@/app/(site)/_components/pages/render";
import { divisionSections } from "@/app/(site)/_components/pages/service/defaults";
import { SERVICE_SECTIONS } from "@/app/(site)/_components/pages/service/sections";
import { getServiceList, getServicePage, hasPublishedServices } from "@/app/(site)/_lib/cms";
import { DIVISIONS, divisionHref, getDivision } from "@/app/(site)/_lib/divisions";
import type { PageSection, PublicServicePage } from "@/app/(site)/_lib/pageContent";

type Props = { params: Promise<{ slug: string }> };

/** Every service the website can show: the built-in ones and those published in the CMS. */
export async function generateStaticParams() {
  const slugs = new Set(DIVISIONS.map((d) => d.slug));
  (await getServiceList())?.divisions.forEach((d) => d.services.forEach((s) => slugs.add(s.slug)));
  return [...slugs].map((slug) => ({ slug }));
}

/**
 * What /services/<slug> shows:
 * - the CMS service when it is published (its card is on the Services page);
 * - otherwise, while no service is published in the CMS at all, the built-in service
 *   with this slug (the 12 original division pages);
 * - otherwise nothing (404). Once the CMS has services, it alone decides which exist.
 */
async function resolve(slug: string): Promise<{ cms: PublicServicePage } | { builtIn: PageSection[]; title: string } | null> {
  const [cms, list] = await Promise.all([getServicePage(slug), getServiceList()]);
  if (cms) return { cms };
  const d = getDivision(slug);
  if (d && !hasPublishedServices(list)) return { builtIn: divisionSections(d), title: d.content.hero.title };
  return null;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const r = await resolve(slug);
  if (!r) return {};
  if ("builtIn" in r) return { title: `${r.title} — Unionists Group` };
  const { card } = r.cms;
  const hero = r.cms.sections.find((s) => s.key === "page-hero")?.content as { title?: string } | undefined;
  return {
    title: `${hero?.title ?? card.title} — Unionists Group`,
    description: card.description,
    alternates: { canonical: divisionHref(slug) },
    openGraph: { title: card.title, description: card.description, images: card.image?.url ? [card.image.url] : undefined },
  };
}

export default async function Page({ params }: Props) {
  const { slug } = await params;
  const r = await resolve(slug);
  if (!r) notFound();

  let sections: PageSection[];
  let fallback: PageSection[] = [];
  if ("builtIn" in r) {
    sections = r.builtIn;
  } else {
    // The card belongs to the Services page. A service whose page isn't written yet still gets a title.
    sections = r.cms.sections.filter((s) => s.key !== "card");
    if (!sections.length) sections = [{ key: "page-hero", type: "page-hero", content: { title: r.cms.card.title, breadcrumb: r.cms.card.title } }];
    const d = getDivision(slug);
    if (d) fallback = divisionSections(d);
  }

  return (
    <SitePage className="service-details-page">
      <a className="skip-link" href="#main">
        Skip to main content
      </a>{" "}
      <SiteHeader active="/product-services" activeItem="/services" />
      <main id="main">{renderSections(`service:${slug}`, { sections }, fallback, SERVICE_SECTIONS)}</main>
      <SiteFooter />
    </SitePage>
  );
}
