import { getQueries } from '@/api/cache/query';
import initializeApollo from '@/apollo/client';
import * as Admin from '@/Components/Admin';
import { Error } from '@/Components/Common/Error';
import { getPageTitle } from '@/utils/page';
import { makeGetUserType } from '@/utils/user';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Head from 'next/head';

function Content() {
  return (
    <Admin.Layout>
      <Head>
        <title>{getPageTitle('Управление кэшем')}</title>
      </Head>
      <Admin.Cache />
    </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 apolloClient = initializeApollo(null, req.headers);
  const getUserType = makeGetUserType({ apolloClient, queryClient });

  try {
    const user = await getUserType({ cookie });

    if (!user.admin) {
      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,
        user,
      },
    };
  } catch (error) {
    return {
      props: {
        error: JSON.stringify(error),
        initialQueryState: dehydrate(queryClient),
        statusCode: 500,
      },
    };
  }
}
