import { getQueries } from '@/api/cache/query';
import { getUser } from '@/api/user/query';
import initializeApollo from '@/apollo/client';
import * as Admin from '@/Components/Admin';
import { Error } from '@/Components/Common/Error';
import { adminRoles } from '@/config/users';
import * as CRMTypes from '@/graphql/crm.types';
import { getPageTitle } from '@/utils/page';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Head from 'next/head';

function Content() {
  return (
    <Admin.Layout>
      <Head>
        <title>{getPageTitle('Управление кэшем')}</title>
      </Head>
      <Admin.CacheQueries />
    </Admin.Layout>
  );
}

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

  return <Content />;
}

/** @type {import('next').GetServerSideProps} */
export async function getServerSideProps({ 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 && adminRoles.includes(x.name))) {
      return {
        props: {
          initialQueryState: dehydrate(queryClient),
          statusCode: 403,
        },
      };
    }

    await queryClient.prefetchQuery(['admin', 'cache', 'queries'], ({ signal }) =>
      getQueries({ signal })
    );

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