import { Login } from '@/components';
import { publicRuntimeConfig, serverRuntimeConfig } from '@/config/runtime';
import { FormStateProvider } from '@/context/form-state';
import axios from 'axios';
import Head from 'next/head';
import { pick } from 'radash';

const { URL_API_CHECK_AUTH } = serverRuntimeConfig;
const { APP_DESCRIPTION } = publicRuntimeConfig;

export function PageHead() {
  return (
    <Head>
      <title>{`Вход - ${APP_DESCRIPTION}`}</title>
      <meta name="description" content={APP_DESCRIPTION} />
    </Head>
  );
}

export default function Page(props) {
  return (
    <FormStateProvider {...props}>
      <PageHead />
      <Login tfa={props.tfa} />
    </FormStateProvider>
  );
}

/** @type {import('next').GetServerSideProps} */
export async function getServerSideProps({ req }) {
  const headers = pick(req.headers, ['auth-mode', 'cookie', 'refresh-token']);
  const tfa = headers['auth-mode'] === 'ldap-tfa';

  try {
    const { data: user } = await axios.get(URL_API_CHECK_AUTH, {
      headers,
    });

    return {
      props: {
        tfa,
        user,
      },
    };
  } catch {
    return {
      props: {
        tfa,
      },
    };
  }
}
