import urls from 'constants/urls';
import getConfig from 'next/config';
import { isServer } from 'tools/common';
import { publicRuntimeConfigSchema, serverRuntimeConfigSchema } from './schema/runtime-config';

const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();

function getUrls() {
  if (isServer()) {
    const { URL_CRM_GRAPHQL_DIRECT, URL_GET_USER_DIRECT, URL_CORE_FINGAP_DIRECT, BASE_PATH, PORT } =
      serverRuntimeConfigSchema.parse(serverRuntimeConfig);

    return {
      PORT,
      BASE_PATH,
      URL_CRM_GRAPHQL: URL_CRM_GRAPHQL_DIRECT,
      URL_GET_USER: URL_GET_USER_DIRECT,
      URL_CORE_FINGAP: URL_CORE_FINGAP_DIRECT,
    };
  }

  const { BASE_PATH } = publicRuntimeConfigSchema.parse(publicRuntimeConfig);

  function withBasePath(url: string) {
    return BASE_PATH + url;
  }

  return {
    BASE_PATH,
    URL_CRM_GRAPHQL: withBasePath(urls.URL_CRM_GRAPHQL_PROXY),
    URL_GET_USER: withBasePath(urls.URL_GET_USER_PROXY),
    URL_CORE_FINGAP: withBasePath(urls.URL_CORE_FINGAP_PROXY),
  };
}

export default getUrls;
