import { getUser } from '@/api/user/query';
import initializeApollo from '@/apollo/client';
import * as Calculation from '@/Components/Calculation';
import { Error } from '@/Components/Common/Error';
import { Grid } from '@/Components/Layout/Page';
import Output from '@/Components/Output';
import { defaultRoles } from '@/config/users';
import * as CRMTypes from '@/graphql/crm.types';
import * as hooks from '@/process/hooks';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Head from 'next/head';

export default function Home(props) {
  hooks.useSentryScope();
  hooks.useMainData();
  hooks.useInsuranceData();
  hooks.useReactions();

  if (props.statusCode !== 200) return <Error {...props} />;

  return (
    <Grid>
      <Head>
        <title>Лизинговый калькулятор - Эволюция</title>
      </Head>
      <Calculation.Form prune={['unlimited']} />
      <Calculation.Settings />
      <Output />
    </Grid>
  );
}
export const makeGetServerSideProps = ({ roles }) =>
  /** @type {import('next').GetServerSideProps} */
  (
    async function ({ req }) {
      const { cookie = '' } = req.headers;

      const queryClient = new QueryClient();

      const user = await queryClient.fetchQuery(['user'], ({ signal }) =>
        getUser({
          headers: {
            cookie,
          },
          signal,
        })
      );

      const apolloClient = initializeApollo();

      try {
        const {
          data: { systemuser },
        } = await apolloClient.query({
          fetchPolicy: 'network-only',
          query: CRMTypes.GetSystemUserDocument,
          variables: {
            domainname: user.domainName,
          },
        });

        if (!systemuser?.roles?.some((x) => x?.name && roles.includes(x.name))) {
          return {
            props: { statusCode: 403 },
          };
        }

        return {
          props: {
            calculation: {},
            initialApolloState: apolloClient.cache.extract(),
            initialQueryState: dehydrate(queryClient),
            statusCode: 200,
          },
        };
      } catch (error) {
        return {
          props: {
            error: JSON.stringify(error),
            statusCode: 500,
          },
        };
      }
    }
  );

export const getServerSideProps = makeGetServerSideProps({ roles: defaultRoles });
