import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import {
  VenuePageView,
  loadVenuePageProps,
} from "@/components/venues/VenuePageView";
import { graphql } from "@/gql";
import { getSeoMetadata } from "@/lib/seo";

type Params = Promise<{ slug: string }>;

const EXCLUDED_SLUGS = ["hele-huset"];

export async function generateMetadata(
  { params }: { params: Params },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { slug } = await params;
  const props = await loadVenuePageProps({ slug });
  if (!props) return null;
  return getSeoMetadata(props.venue, parent);
}

export async function generateStaticParams() {
  const allVenueSlugsQuery = graphql(`
    query allVenueSlugs {
      pages(contentType: "venues.VenuePage", limit: 100) {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allVenueSlugsQuery, {});

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.pages) {
    throw new Error(
      "Failed to generate static params for subpages of /lokaler"
    );
  }

  return data.pages
    .filter((page) => !EXCLUDED_SLUGS.includes(page.slug))
    .map((page) => ({
      slug: page.slug,
    }));
}

export default async function Page({ params }: { params: Params }) {
  const { slug } = await params;
  if (EXCLUDED_SLUGS.includes(slug)) {
    return notFound();
  }
  const props = await loadVenuePageProps({ slug });
  if (!props) return notFound();
  return <VenuePageView {...props} />;
}
