import type { GetServerSideProps, GetServerSidePropsContext } from 'next';

import { TOKEN_COOKIE_NAME } from '~/lib/auth/constants';
import PageLoading from '~/src/components/PageLoading';

const COOKIES_TO_CLEAR = [TOKEN_COOKIE_NAME, 'auth0State'];

const toSingleQueryParam = (
  value: string | string[] | undefined
): string | undefined => {
  if (Array.isArray(value)) return value.length > 0 ? value[0] : undefined;
  return value;
};

const getCookiesToClear = (
  req: GetServerSidePropsContext['req'],
  cookiesToClear: string[]
): string[] => {
  const cookies = req.headers.cookie?.split(';').filter(Boolean) ?? [];

  const match = cookies.filter((cookie) => {
    const name = cookie.split('=', 1)[0].trim();
    return cookiesToClear.includes(name);
  });

  const clearedCookies = match.map((name) => {
    const isProduction = process.env.NODE_ENV === 'production';
    return `${name}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly;${isProduction ? ' Secure;' : ''} SameSite=Lax`;
  });

  return clearedCookies;
};

export const getServerSideProps: GetServerSideProps = async ({
  req,
  res,
  query,
}) => {
  const redirectPath = toSingleQueryParam(query.redirectPath);
  const prompt = toSingleQueryParam(query.prompt);

  // Clear some cookies before redirecting to the login api endpoint.
  const cookies = getCookiesToClear(req, COOKIES_TO_CLEAR);
  if (cookies.length > 0) {
    res.setHeader('Set-Cookie', cookies);
  }

  const params = new URLSearchParams();
  params.append('callbackUrl', redirectPath || '/');
  if (prompt) params.append('prompt', prompt);

  return {
    redirect: {
      destination: `/api/auth/login?${params.toString()}`,
      permanent: false,
    },
  };
};

const LoginPage = () => {
  return <PageLoading />;
};

export default LoginPage;
