import { TideClientConfig } from "@qite/tide-client";
import { isNil } from "lodash";
import { ApiSettingsState } from "../types";

export function buildTideClientConfig(
  settings?: ApiSettingsState
): TideClientConfig {
  const HOST = settings?.apiUrl || process.env.REACT_APP_BOOKING_HOST;
  const API_KEY = settings?.apiKey || process.env.REACT_APP_BOOKING_API_KEY;
  const token = selectAgentToken();

  if (isNil(HOST)) {
    throw Error(`Environment variable "HOST" was not set.`);
  }

  if (isNil(API_KEY)) {
    throw Error(`Environment variable "API_KEY" was not set.`);
  }

  return {
    host: HOST,
    apiKey: API_KEY,
    token: token,
  };
}

const selectAgentToken = (): string | undefined => {
  let token: string | null = null;
  if (typeof sessionStorage !== "undefined") {
    token = sessionStorage.getItem("token");
  }
  if (token === null && typeof localStorage !== "undefined") {
    token = localStorage.getItem("token");
  }
  return token ?? undefined;
};
