/* eslint-disable object-curly-newline */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable no-underscore-dangle */
import { createContext } from 'react';
import RootStore from './root';

/** @type{RootStore} */
let store;
export const StoreContext = createContext(store);

export function initializeStore(initialData) {
  const _store = store ?? new RootStore();

  if (initialData) {
    const { calculation, tables } = initialData;

    if (calculation?.values) _store.$calculation.$values.hydrate(calculation.values);
    if (calculation?.statuses) _store.$calculation.$status.hydrate(calculation.statuses);
    if (calculation?.options) _store.$calculation.$options.hydrate(calculation.options);

    if (tables?.insurance) {
      _store.$tables.insurance.hydrate({
        values: tables.insurance.values,
        options: tables.insurance.options,
        statuses: tables.insurance.statuses,
      });
    }
  }

  if (typeof window === 'undefined') return _store;
  if (!store) store = _store;

  return _store;
}
