import { getClient } from "@/app/client";
import { PageHeader } from "@/components/general/PageHeader";
import { NewsList } from "@/components/news/NewsList";
import { NewsFragment, NewsIndexFragment, newsQuery } from "@/lib/news";

export type NewsIndexViewProps = {
  index: NewsIndexFragment;
  news: NewsFragment[];
};

export async function loadNewsIndexProps(overrides?: {
  indexOverride?: NewsIndexFragment;
}): Promise<NewsIndexViewProps> {
  const { data, error } = await getClient().query(newsQuery, {});
  if (error) throw new Error(error.message);
  const index = overrides?.indexOverride ?? (data?.index as NewsIndexFragment | undefined);
  if (!index) throw new Error("Failed to load /aktuelt");
  const news = (data?.news ?? []) as NewsFragment[];
  return { index, news };
}

export function NewsIndexView({ index, news }: NewsIndexViewProps) {
  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} align="left" />
      <NewsList news={news} />
    </main>
  );
}
