import * as apiIUS from '@/api/ius/query';
import { Form } from '@/components/Form';
import type { PageProps } from '@/types/page';
import { withError } from '@/utils/error';
import { getPageUrlParams } from '@/utils/url';
import type { Metadata } from 'next';

export async function generateMetadata(pageProps: PageProps): Promise<Metadata> {
  const pageUrlParams = getPageUrlParams(pageProps);
  const { title } = await apiIUS.getConfig({ pageUrlParams });
  const text = `${title} | Эволюция`;

  return {
    description: text,
    openGraph: {
      description: text,
      title: text,
    },
    title: text,
  };
}

export default async function Page(pageProps: PageProps) {
  return withError({
    render: async () => {
      const pageUrlParams = getPageUrlParams(pageProps);

      return Promise.all([
        apiIUS.getData({ pageUrlParams }),
        apiIUS.getMetaData({ pageUrlParams }),
        apiIUS.getConfig({ pageUrlParams }),
        apiIUS.getDocumentTypes({ pageUrlParams }),
        apiIUS.getDocuments({ pageUrlParams }),
      ]).then(([data, metaData, { title }, documentTypes, documents]) => {
        const props = { data, documentTypes, documents, metaData, pageUrlParams, title };

        return <Form {...props} />;
      });
    },
  });
}
