import { getServerAuthConfig, pathsConfig } from '@kit/shared/config';

import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';

import PasswordOption from './components/PasswordOption';
import { SignInPageClientRedirect } from './components/SignInPageClientRedirect';

interface SignInPageProps {
  searchParams: Promise<{
    invite_token?: string;
    next?: string;
  }>;
}

export const generateMetadata = async () => {
  const i18n = await createI18nServerInstance();

  return {
    title: i18n.t('auth:signIn'),
  };
};

async function SignInPage({ searchParams }: SignInPageProps) {
  const { invite_token: inviteToken, next: returnPath = pathsConfig.app.home } =
    await searchParams;

  const authConfig = await getServerAuthConfig();

  if (authConfig.providers.password) {
    return (
      <PasswordOption
        inviteToken={inviteToken}
        returnPath={returnPath}
        providers={authConfig.providers}
      />
    );
  }

  if (authConfig.providers.oAuth.includes('keycloak')) {
    return <SignInPageClientRedirect />;
  }

  return null;
}

export default withI18n(SignInPage);
