import { getFlatPageData, getSeoData } from '@akinon/next/data/server';
import { withSegmentDefaults } from '@akinon/next/hocs/server';
import {
  AsyncPageProps,
  Metadata,
  ResolvedPageProps
} from '@akinon/next/types';
import { parsePzParams } from '@akinon/next/utils/pz-segments';
import logger from '@akinon/next/utils/log';
import settings from '@theme/settings';
import { notFound } from 'next/navigation';

export async function generateMetadata(
  props: AsyncPageProps<{ pk: number }>
): Promise<Metadata> {
  const params = await props.params;
  const { locale } = parsePzParams(params, settings);

  try {
    const data = await getFlatPageData({ pk: params.pk, locale });
    const flatPage = data?.flat_page;

    if (!flatPage) {
      return {};
    }

    const localizedUrl = flatPage.flatpageprettyurl_set?.find(
      (entry) => entry.language === locale
    )?.url;
    const seoUrl = localizedUrl ?? flatPage.url;

    if (!seoUrl) {
      return {};
    }

    const seo = await getSeoData(seoUrl, locale);

    if (!seo?.title && !seo?.description && !seo?.keywords) {
      logger.debug('No CMS SEO entry for flat-page', {
        pk: params.pk,
        seoUrl,
        locale
      });
      return {};
    }

    return {
      ...(seo.title ? { title: seo.title } : {}),
      ...(seo.description ? { description: seo.description } : {}),
      ...(seo.keywords ? { keywords: seo.keywords } : {})
    };
  } catch (error) {
    logger.warn('flat-page generateMetadata failed', {
      pk: params.pk,
      locale,
      error
    });
    return {};
  }
}

async function Page({ params }: ResolvedPageProps<{ pk: number }>) {
  try {
    const data = await getFlatPageData({ pk: params.pk });

    return (
      <div className="container mx-auto py-6">
        <div
          className="mx-auto prose prose-headings:text-primary"
          dangerouslySetInnerHTML={{ __html: data.flat_page.content }}
        />
      </div>
    );
  } catch (error) {
    notFound();
  }
}

export default withSegmentDefaults(Page, { segmentType: 'page' });
