import * as React from 'react';
import redirect from 'utils/redirect';
import NotFound from 'pages/404';
import { IContext } from 'typings/context';
import { isNationalIdValid } from 'utils/helpers';

const SsnRedirect = () => <NotFound />;

/**
 * Redirects for /[ssn]
 *
 * This route catches a lot of old routes like /reikningar /hreyfingalisti etc.
 * Which we would want to attempt to redirect to the correct path.
 *
 * If logged in user is staff
 * /[valid_ssn] -> /[valid_ssn]/thjonustur
 * /thjonustur?ssn=[valid_ssn] => /[valid_ssn]/thjonustur
 * /[invalid_ssn] => /staff
 *
 * If logged in user has a ssn
 * /[some_handle] -> /[logged_in_ssn]/[some_handle]
 * /[logged_in_ssn] -> /[logged_in_ssn]/thjonsutur (home page)
 *
 * ie.
 * /thjonustur -> /[ssn]/thjonustur
 * /reikningar -> /[ssn]/reikningar
 *
 *
 * If logged in user does not have a ssn but has msisdn
 * we assume that it's an unregistered msisdn
 * /[some_handle] -> /oskrad/thjonustur/[unregistered_sub_id]
 *
 */

SsnRedirect.getInitialProps = (context: IContext) => {
  const { user, query, asPath } = context;

  if (user?.isStaff) {
    if (isNationalIdValid(query.ssn as string)) {
      const subroute =
        asPath?.split('?')[0] !== `/${query.ssn}` ? asPath?.split('?')[0] : undefined;
      redirect(context, `/${query.ssn}${subroute || '/thjonustur'}`);
      return {};
    }

    redirect(context, '/staff');
    return {};
  }

  if (user?.profileSsn) {
    if (user.profileSsn === asPath?.replace('/', '')) {
      redirect(context, `/${user.profileSsn}/thjonustur`);
      return {};
    }

    redirect(context, `/${user.profileSsn}${asPath || '/thjonustur'}`);

    return {};
  }

  if (user?.msisdn) {
    redirect(context, `/oskrad/thjonusta/${user.msisdn}`);
    return {};
  }

  return {};
};

export default SsnRedirect;
