import * as React from 'react';

import redirect from 'utils/redirect';
import NotFound from 'pages/404';
import { IContext } from 'typings/context';
import { SINGLE_SUBSCRIPTION } from 'graphql/queries/singleSubscription';

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

/**
 * Redirects for /thjonusta/*
 *
 * If logged in user is staff
 * /thjonusta/[unregistered_sub_id] -> /oskrad/thjonusta/[unregistered_sub_id]
 * /thjonusta/[valid_sub_id] -> /[sub_user_ssn]/thjonusta/[sub_id]
 * /thjonusta/[invalid_sub_id] -> /staff
 *
 * If logged in user has a ssn
 * /thjonusta/[sub_id] -> /[logged_in_ssn]/thjonusta/[sub_id]
 *
 *
 * If logged in user does not have a ssn but has msisdn
 * we assume that it's an unregistered msisdn
 * /thjonusta/[unregistered_sub_id] -> /oskrad/thjonustur/[unregistered_sub_id]
 */

Thjonusta.getInitialProps = async (context: IContext) => {
  const { user, apolloClient, asPath, query } = context;
  const subscriptionId = query?.subscriptionId?.[0];

  if (!user?.isStaff && subscriptionId) {
    if (user?.profileSsn) {
      redirect(context, `/${user.profileSsn}${asPath}`);
      return {};
    }

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

  if (user?.isStaff) {
    const { data } = await apolloClient.query({
      query: SINGLE_SUBSCRIPTION,
      variables: {
        subscriptionId,
      },
    });

    if (data.subscription) {
      const { subscription } = data;

      if (subscription.rateplan?.typeId === 'unregistered') {
        redirect(context, `/oskrad${asPath}`);
        return {};
      }

      redirect(context, `/${subscription.ssn}${asPath}`);
      return {};
    }

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

  return {};
};

export default Thjonusta;
