import { enableStaticRendering } from 'mobx-react';

import Authentication from './authentication';
import Hradleid from './hradleid';
import Payments from './payment';
import Steps from './steps';
import UI from './ui';

const isServer = typeof window === 'undefined';

enableStaticRendering(isServer);

let store: any = null;

export default function initializeStore(state = {}, query: any, cookies?: string | object | null) {
  if (!query) {
    return;
  }

  const { customerId, ssn } = query;

  const subscriptionId = Array.isArray(query.subscriptionId)
    ? query.subscriptionId[0]
    : query.subscriptionId;

  if (isServer) {
    const authentication = new Authentication(
      state,
      {
        ssn: ssn as string,
        subscriptionId: subscriptionId as string,
        customerId: customerId as string,
      },
      cookies,
    );

    return {
      authentication,
      ui: new UI(state),
      steps: new Steps(state),
      payments: new Payments(state),
      hradleid: new Hradleid(state),
    };
  }
  if (store === null) {
    const authentication = new Authentication(state, { ssn, subscriptionId, customerId }, '');

    store = {
      authentication,
      ui: new UI(state),
      steps: new Steps(state),
      payments: new Payments(state),
      hradleid: new Hradleid(state),
    };
  }
  return store;
}
