/**
 * Created by vivek on 3/5/17.
 */
import 'whatwg-fetch';
import { GA, decompressJsonObject } from '@capillarytech/cap-ui-utils';
import get from 'lodash/get';
import { loadItem, clearItem } from './localStorageApi';
import config from '../config/app';
import pathConfig from '../config/path';
import getSchema from './getSchema';
import * as API from '../utils/ApiCaller';
import { addBaseToTemplate, transformCustomFieldsData } from '../utils/commonUtils';
import { EMAIL, SMS, TRANSACTION } from '../v2Containers/CreativesContainer/constants';
let API_ENDPOINT = config.development.api_endpoint;
let EXPORT_API_ENDPOINT = config.development.exports_api_endpoint;
let CAMPAIGNS_API_ENDPOINT = config.development.campaigns_api_endpoint;
let CAMPAIGNS_API_ORG_ENDPOINT = config.development.campaigns_api_org_endpoint;
let LIQUID_API_ENDPOINT = config.development.liquid_endpoint;
let MEMBERCARE_API_ENDPOINT = config.development.membercare_api_endpoint;
let IRIS_API_ENDPOINT = config.development.iris_api_endpoint;
let ADIONA_API_ENDPOINT = config.development.adiona_api_endpoint;

let API_AUTH_ENDPOINT = config.development.auth_endpoint;
let ARYA_ENDPOINT = config.development.arya_endpoint;
let SUBSCRIPTION_API_ENDPOINT = config.development.subscription_api_endpoint;
if (process.env.NODE_ENV === 'production') {
  API_ENDPOINT = config.production.api_endpoint;
  CAMPAIGNS_API_ENDPOINT = config.production.campaigns_api_endpoint;
  CAMPAIGNS_API_ORG_ENDPOINT = config.production.campaigns_api_org_endpoint;
  API_AUTH_ENDPOINT = config.production.auth_endpoint;
  ARYA_ENDPOINT = config.production.arya_endpoint;
  SUBSCRIPTION_API_ENDPOINT = config.production.subscription_api_endpoint;
  EXPORT_API_ENDPOINT = config.production.exports_api_endpoint;
  LIQUID_API_ENDPOINT = config.production.liquid_endpoint;
  MEMBERCARE_API_ENDPOINT = config.production.membercare_api_endpoint;
  IRIS_API_ENDPOINT = config.production.iris_api_endpoint;
  ADIONA_API_ENDPOINT = config.production.adiona_api_endpoint;
}
let requestCallerName = '';
const isProd = process.env.NODE_ENV === 'production';
const { getCallerName, tracker } = GA;
function parseJSON(response) {
  return response.json();
}

function getUrlWithQueryParams({url, queryParams}) {
  let updatedUrl = url;
  Object.entries(queryParams).forEach(([key, value]) => {
    if (value !== undefined) {
      updatedUrl += `${key}=${key === 'name' ? encodeURIComponent(value) : value}&`;
    }
  });
  return updatedUrl;
}

function redirectIfUnauthenticated(response) {
  const isUnauthorized = response.status === 401;
  const isLoginPage = window.location.pathname.indexOf('auth/login') !== -1;
  const isAuthUserCall = response.url.split('auth')[1] && response.url.split('auth')[1].split("?")[0] === '/user';
  if (isUnauthorized) {
    if (isProd) {
      const originUrl = window.location.origin;
      clearLocalStorage();
      window.location = `${originUrl}/auth/logout`;
    } else {
      if (isLoginPage && isAuthUserCall) return;
      clearLocalStorage();
      const loginPage = `${pathConfig.publicPath}${config.development.login_url}`;
      window.location = `${loginPage}`;
    }
  }
}

function clearLocalStorage() {
  clearItem('token');
  clearItem('orgID');
  clearItem('ouId');
  clearItem('isLoggedIn');
  clearItem('user');
}

function checkStatus(response) {
  const { status, statusText } = response || {};
  if (status < 200 || status > 300) {
    tracker.trackException({
      description: `API Error ${requestCallerName} returned ${status}`,
      fatal: true,
      apiError: true,
      statusCode: status,
    });
  }
  if ((status >= 200 && status < 300) || [400, 409, 413, 500].includes(response.status)) {
    return response;
  }
  const isLoginPage = window.location.pathname.indexOf('/login') !== -1;
  if (!isLoginPage) redirectIfUnauthenticated(response);

  const error = new Error(statusText);
  error.response = response;
  error.isError = true;
  error.status = status;
  throw error;
}

function showSomethingwentWrong() {
  window.history.pushState({}, '', `${pathConfig.publicPath}/v2/somethingwentwrong`);
}

function request(url, options, handleUnauthorizedStatus) {
  try {
    requestCallerName = getCallerName();
  } catch (e) {

  }
  const fetchUrl = url.indexOf('?') !== -1 ? `${url}&time=${Date.now()}` : `${url}?time=${Date.now()}`;
  return fetch(fetchUrl, options)
    .then((response) => {
      if (response.status === 403 && handleUnauthorizedStatus) {
        showSomethingwentWrong();
      }
      return checkStatus(response);
    })
    .then(parseJSON)
    .catch((error) => error);
}

function getAPICallObject(method, body, isFileUpload = false, loadCampaignHeaders = false, orgUnitId = false, allowOrgInProd = false) {
  const token = loadItem('token');
  const orgID = loadItem('orgID');
  const user = loadItem('user');
  let headers;
  if (isFileUpload) {
    headers = {};
  } else {
    headers = {
      'Content-Type': 'application/json',
    };
  }

  if (loadCampaignHeaders) {
    headers['X-CAP-ORG'] = orgID;

    if (token !== undefined) {
      headers['X-CAP-CT'] = token;
    }
    if (orgUnitId) {
      headers['X-CAP-OU'] = orgUnitId;
    }
  } else {
    if (user && user.refID) {
      headers['X-CAP-REMOTE-USER'] = user.refID;
    }

    if ((allowOrgInProd || process.env.NODE_ENV !== "production") && orgID !== undefined) {
      headers["X-CAP-API-AUTH-ORG-ID"] = orgID;
    }

    if (process.env.NODE_ENV !== 'production' && token !== undefined) {
      headers.Authorization = `Bearer ${token}`;
    }
  }

  const requestObj = {
    method,
    mode: 'cors',
    headers: new Headers(headers),
  };

  if (process.env.NODE_ENV === 'production') {
    requestObj.credentials = 'same-origin';
  }

  if (body && !isFileUpload) {
    requestObj.body = JSON.stringify(body);
  } else if (body && isFileUpload) {
    requestObj.body = body;
  }
  return requestObj;
}

function getLoyaltyAPICallObject(method, body, notStringify) {
  const token = loadItem('token');
  const orgID = loadItem('orgID');
  const user = loadItem('user');
  const headers = {};

  if (!notStringify) {
    headers['Content-Type'] = 'application/json';
  }

  if (user && user.refID) {
    headers['X-CAP-REMOTE-USER'] = user.refID;
  }

  if (process.env.NODE_ENV !== 'production' && orgID !== undefined) {
    headers['X-CAP-API-AUTH-ORG-ID'] = orgID;
  }

  if (token !== undefined) {
    headers.Authorization = `Bearer ${token}`;
  }
  const requestObj = {
    method,
    mode: 'cors',
    headers: new Headers(headers),
  };

  if (process.env.NODE_ENV === 'production') {
    requestObj.credentials = 'same-origin';
  }

  if (body && !notStringify) {
    requestObj.body = JSON.stringify(body);
  } else {
    requestObj.body = body;
  }

  return requestObj;
}

// Authentication
export const authorize = (user) => {
  const body = {
    username: user.username,
    password: user.password,
  };

  const requestObj = {
    method: 'POST',
    headers: new Headers({
      'Content-Type': 'application/json',
    }),
  };
  if (process.env.NODE_ENV === 'production') {
    requestObj.credentials = 'same-origin';
  }
  requestObj.body = JSON.stringify(body);
  return request(`${API_AUTH_ENDPOINT}/login`, requestObj);
};

export const logout = () => {
  const url = `${API_AUTH_ENDPOINT}/logout`;
  return request(url, getAPICallObject('GET'));
};

export const changeProxyOrg = (orgId) => {
  const url = `${API_AUTH_ENDPOINT}/setProxy/${orgId}`;
  return request(url, getAPICallObject('Post'));
};

export const getSidebar = () => {
  //Insert your call here for getting sidebar
  const url = `${API_ENDPOINT}/getSidebar`;
  const response = {response: {sidebar: [url]}};
  // return request(url, getAPICallObject('GET'));
  return response;
};

// if 403, show SWR page
export const getUserData = () => {
  const url = `${API_AUTH_ENDPOINT}/user?include_features=1`;
  return request(url, getAPICallObject('GET'), true);
};

export const createTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/SMS`;
  return request(url, getAPICallObject('POST', template));
};

export const editTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/SMS`;
  return request(url, getAPICallObject('POST', template));
};

export const createWeChatTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/WECHAT`;
  return request(url, getAPICallObject('POST', template));
};

export const createMobilePushTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/MOBILEPUSH`;
  return request(url, getAPICallObject('POST', template));
};
//this is for new mobile push templates
export const createMobilePushTemplateV2 = (template) => {
  const url = `${API_ENDPOINT}/templates/MOBILEPUSH`;
  return request(url, getAPICallObject('POST', template));
};

export const createWebPushTemplate = (template) => {
  const url = `${API_ENDPOINT}/templates/WEBPUSH`;
  return request(url, getAPICallObject('POST', template));
};

export const duplicateTemplate = ({id, channel}) => {
  const url = `${API_ENDPOINT}/templates/duplicate/${id}/${channel}`;
  return request(url, getAPICallObject('GET'));
};

export const getFTPServers = () => {
  const url = `${EXPORT_API_ENDPOINT}/ftplist`;
  return request(url, getAPICallObject('GET'));
};

export const editWeChatTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/WECHAT`;
  return request(url, getAPICallObject('POST', template));
};

export const createEmailTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/EMAIL`;
  return request(url, getAPICallObject('POST', template));
};

export const createEbillTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/EBILL`;
  return request(url, getAPICallObject('POST', template));
};

export const createChannelWiseTemplate = ({ channel, template }) => {
  const url = `${API_ENDPOINT}/templates/${channel}`;
  return request(url, getAPICallObject('POST', template));
};


export const getTemplateDetails = async ({id, channel}) => {
  const url = `${API_ENDPOINT}/templates/v1/${id}/${channel ? channel.toUpperCase() : SMS}`;
  const compressedTemplatesData = await request(url, getAPICallObject('GET'));
  const {response = ''} = compressedTemplatesData;
  const decompressData = decompressJsonObject(response);
  if (channel?.toUpperCase() === EMAIL) {
    return { ...compressedTemplatesData, response: addBaseToTemplate(decompressData) };
  }
  return { ...compressedTemplatesData, response: decompressData};
};

export const getDomainProperties = (channels, orgUnitId) => {
  const queryString = channels?.map((channel) => `channel=${channel?.toUpperCase()}`)?.join('&');
  const url = `${CAMPAIGNS_API_ORG_ENDPOINT}/meta/domainProperties?${queryString}`;
  return request(url, getAPICallObject('GET', null, false, true, orgUnitId));
};

export const getMediaDetails = async ({ id }) => {
  const url = `${API_ENDPOINT}/media/${id}`;
  return request(url, getAPICallObject('GET'));
};

export const getAllTemplates = async ({channel, queryParams = {}}) => {
  const url = getUrlWithQueryParams({
    url: `${API_ENDPOINT}/templates/v1/${channel}?`,
    queryParams,
  });
  const compressedTemplatesData = await request(url, getAPICallObject('GET'));
  const {response = ''} = compressedTemplatesData;
  return { ...compressedTemplatesData, response: decompressJsonObject(response)};
};

export const deleteTemplate = ({channel, id}) => {
  const url = `${API_ENDPOINT}/templates/${id}/${channel}`;
  return request(url, getAPICallObject('DELETE'));
  //return API.deleteResource(url);
};

export const archiveTemplate = ({ channel, id }) => {
  const url = `${API_ENDPOINT}/templates/archive/${id}/${channel}`;
  return request(url, getAPICallObject('PUT'));
};

export const unarchiveTemplate = ({ channel, id }) => {
  const url = `${API_ENDPOINT}/templates/unarchive/${id}/${channel}`;
  return request(url, getAPICallObject('PUT'));
};

export const bulkArchiveTemplates = ({ channel, ids }) => {
  const url = `${API_ENDPOINT}/templates/archive/bulk/${channel}`;
  return request(url, getAPICallObject('PUT', { ids }));
};

export const bulkUnarchiveTemplates = ({ channel, ids }) => {
  const url = `${API_ENDPOINT}/templates/unarchive/bulk/${channel}`;
  return request(url, getAPICallObject('PUT', { ids }));
};

export const deleteRcsTemplate = ({ templateName }) => {
  const url = `${API_ENDPOINT}/templates/${templateName}/RCS`;
  return request(url, getAPICallObject('DELETE'))
    .then((result) => result)
    .catch((error) => {
      throw error;
    });
};

export const getAllAssets = ({assetType, queryParams = {}}) => {
  const url = getUrlWithQueryParams({
    url: `${API_ENDPOINT}/assets/${assetType}?`,
    queryParams,
  });
  // const url = `https://nightly.capillary.in/arya/api/v1/creatives/assets/${assetType}?query=${JSON.stringify(queryParams)}`;
  return request(url, getAPICallObject('GET'));
};

export const deleteAssetById = ({assetId, assetType}) => {
  const url = `${API_ENDPOINT}/assets/${assetId}/${assetType}`;
  return request(url, getAPICallObject('DELETE'));
  // return API.deleteResource(url);
};

export const uploadFile = ({
  file, assetType, fileParams, mode, wechatParams, whatsappParams,
}) => {
  const data = new FormData();
  let fileName = '';
  try {
    fileName = encodeURIComponent(file?.name || '');
  } catch (error) {
    fileName = file?.name || '';
  }
  // Creating a new File object with the modified filename
  const modifiedFile = new File([file], fileName, {
    type: file?.type,
  });
  // Append the modified file to the FormData object
  data.append('file', modifiedFile);
  data.append('fileParam', JSON.stringify(fileParams));
  if (mode) {
    data.append('mode', mode);
  }
  if (wechatParams) {
    data.append('source', wechatParams.source);
    data.append('appId', wechatParams.appId);
    data.append('appSecret', wechatParams.appSecret);
  }
  if (whatsappParams) {
    const { source, wabaId, accessToken, access_token, phoneId, hostName, baseUrl } = whatsappParams;
    data.append('source', source);
    data.append('wabaId', wabaId);
    data.append('accessToken', accessToken || access_token);
    data.append('phoneId', phoneId);
    data.append('hostName', hostName);
    data.append('baseUrl', baseUrl);
  }
  const url = `${API_ENDPOINT}/assets/${assetType}`;
  // return API.post(url, data, true);
  return request(url, getAPICallObject('POST', data, true));
};

export const getUserList = () => {
  const url = `${API_AUTH_ENDPOINT}/org/users`;
  return API.get(url);// request(url, getAPICallObject('GET'));
};

export const fetchSchemaForEntity = async ({queryParams}) => {
  if (queryParams.version === "v2" && queryParams.type === "LAYOUT") {
    const schema = getSchema(queryParams.layout);
    // Added async/await to ensure the schema object is resolved before returning it
    return schema.then((layout) => layout).catch((err) => {
      console.error(err);
    });
  }
  const url = `${API_ENDPOINT}/meta/${queryParams.type}?query=${JSON.stringify(queryParams)}`;
  const result = await request(url, getAPICallObject('GET'));// request(url, getAPICallObject('GET'));
  const customFields = get(result, 'response.metaEntities.custom', {});
  if (customFields && Object.keys(customFields)?.length > 0) {
    const transformedData = transformCustomFieldsData(customFields);
    result.response.metaEntities.custom = transformedData;
  }
  return result;
};

export const fetchWeCrmAccounts = (sourceName) => {
  let url = `${API_ENDPOINT}/meta/wecrm`;
  if (sourceName) {
    url += `?source_name=${sourceName.toUpperCase()}`;
  }
  return request(url, getAPICallObject('GET'));
};
export const getIosCtas = ({licenseCode}) => {
  const url = `${API_ENDPOINT}/meta/ioscta?account_license=${licenseCode}`;
  return request(url, getAPICallObject('GET'));
};

export const sendZippedFile = (file) => {
  const data = new FormData();
  data.append('file', file);
  const url = `${API_ENDPOINT}/meta/uploadZip`;
  return request(url, getAPICallObject('POST', data, true));
};

export const getCmsTemplateSettings = (cmsType, projectId, cmsMode, langId, isEdmSupport) => {
  const url = `${API_ENDPOINT}/cms/getDetails?type=${cmsType}&projectId=${projectId}&cmsMode=${cmsMode}&langId=${langId}&isEdmSupport=${isEdmSupport ? 1 : 0}`;
  return API.get(url);
};

export const getCmsTemplateSettingsV2 = (cmsType, projectId, cmsMode, langId, isEdmSupport, isBEEAppEnable) => {
  const url = `${API_ENDPOINT}/cms/v2/getDetails/?type=${cmsType}&projectId=${projectId}&cmsMode=${cmsMode}&langId=${langId}&isEdmSupport=${isEdmSupport ? 1 : 0}&isBEEAppEnable=${isBEEAppEnable}`;
  return API.get(url);
};

export const getCmsAccounts = (cmsType) => {
  const url = `${API_ENDPOINT}/cms/accounts?type=${cmsType}`;
  return API.get(url);
};

export const getCmsTemplateData = (cmsType, projectId, langId) => {
  const url = `${API_ENDPOINT}/cms/getContent?type=${cmsType}&projectId=${projectId}&langId=${langId}`;
  return API.get(url);
};

export const getCmsTemplateDataV2 = (cmsType, projectId, langId) => {
  const url = `${API_ENDPOINT}/cms/v2/getContent?type=${cmsType}&projectId=${projectId}&langId=${langId}`;
  return API.get(url);
};

export const getCmsData = (cmsType, projectId, langId) => {
  const url = `${API_ENDPOINT}/cms/getCmsData?type=${cmsType}&projectId=${projectId}&langId=${langId}`;
  return API.get(url);
};

export const getEdmTemplates = async () => {
  const url = `${API_ENDPOINT}/templates/email/default`;
  const compressedEdmTemplates = await request(url, getAPICallObject('GET'));
  const response = get(compressedEdmTemplates, 'response', '');
  const decompressedEdmTemplates = decompressJsonObject(response);
  return { ...compressedEdmTemplates, response: addBaseToTemplate(decompressedEdmTemplates) };
};

export const getDefaultBeeTemplates = async () => {
  const url = `${API_ENDPOINT}/templates/v2/email/default`;
  const compressedDefaultBeeTemplates = await request(url, getAPICallObject('GET'));
  const response = get(compressedDefaultBeeTemplates, 'response', '');
  const decompressedBeeTemplates = decompressJsonObject(response);
  return { ...compressedDefaultBeeTemplates, response: addBaseToTemplate(decompressedBeeTemplates) };
};

// All about line

export const createLineTemplate = (template) => {
  const url = `${API_ENDPOINT}/templates/LINE`;
  return request(url, getAPICallObject('POST', template));
};

export const createRcsTemplate = ({channel, template}) => {
  const url = `${API_ENDPOINT}/templates/RCS`;
  return request(url, getAPICallObject('POST', template));
};

export const createViberTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/VIBER`;
  return request(url, getAPICallObject('POST', template));
};

export const createFacebookADTemplate = ({template}) => {
  const url = `${API_ENDPOINT}/templates/FACEBOOK`;
  return request(url, getAPICallObject('POST', template));
};

export const getLocizMessage = async (locale) => {
  const appName = 'creatives_v2';
  const url = `${ARYA_ENDPOINT}/translations/${appName}/${locale}`;
  const response = await request(url, getAPICallObject('GET'));
  return response;
};

export const askAiraForLiquid = async ({ templateContent = '', errorMessage = '' }) => {
  const url = `${ARYA_ENDPOINT}/ask-aira-service/creatives_ai/liquidValidation`;
  const response = await request(
    url,
    getAPICallObject("POST", {
      temperature: 0.8,
      templateContent,
      parserError: errorMessage,
    })
  );
  return response;
};

export const getUnsubscribeUrl = () => {
  const body = {
    orgUnitId: -1,
    source: 'INSTORE',
    accountId: '',
    priority: 'BULK',
    channel: 'mobile',
  };
  const url = `${SUBSCRIPTION_API_ENDPOINT}/unsubscribeUrl`;
  return request(url, getAPICallObject('POST', body));
};

export const getMarketingObjectives = (channel) => request(
  `${CAMPAIGNS_API_ENDPOINT}/socialObjectives?channel=${channel}`,
  getAPICallObject('GET', null, false, true),
);

export const getAllLineStickers = () => request(`${API_ENDPOINT}/meta/sticker`, getAPICallObject('GET'));


export const createCustomRow = (data) => {
  const url = `${API_ENDPOINT}/cms/saveRows`;
  return request(url, getAPICallObject('POST', data));
};

export const getFacebookPreview = ({previewData}) => {
  const url = `${API_ENDPOINT}/facebook/getPreview`;
  return request(url, getAPICallObject('POST', previewData));
};


export const getOrgOUs = ({ orgID }) => {
  const url = `${ARYA_ENDPOINT}/org/${orgID}/oulist`;
  return request(url, getAPICallObject('GET'));
};

export const getOrgLevelCampaignSettings = () => {
  const url = `${CAMPAIGNS_API_ORG_ENDPOINT}/settings`;
  return request(url, getAPICallObject('GET', null, false, true));
};

export const getFacebookVideoId = ({videoUrl, accessToken, actId, pageAccessToken, pageId}) => {
  const url = `${API_ENDPOINT}/facebook/getFacebookVideoId`;
  return request(url, getAPICallObject('POST', {videoUrl, accessToken, actId, pageAccessToken, pageId}));
};

export const createBulkSMSTemplate = ({templates}) => {
  const url = `${API_ENDPOINT}/templates/bulk/sms`;
  return request(url, getAPICallObject('POST', templates));
};

export const checkBulkDuplicates = (data) => {
  const url = `${API_ENDPOINT}/templates/bulk/sms/checkDuplicates`;
  return request(url, getAPICallObject('POST', data));
};

export const createWhatsappTemplate = ({payload, gupshupMediaFile }) => {
  const data = new FormData();
  data.append('payload', JSON.stringify(payload));
  if (Array.isArray(gupshupMediaFile) && gupshupMediaFile?.length) {
    gupshupMediaFile.forEach((file, index) => {
      data.append(`gupshupMediaFile_${index}`, file);
    });
  } else {
    data.append('gupshupMediaFile', gupshupMediaFile);
  }
  const url = `${API_ENDPOINT}/templates/WHATSAPP`;
  return request(url, getAPICallObject('POST', data, true));
};

export const getSenderDetails = (channel, orgUnitId) => {
  const url = `${CAMPAIGNS_API_ORG_ENDPOINT}/meta/domainProperties?channel=${channel}`;
  return request(url, getAPICallObject('GET', null, false, true, orgUnitId));
};

export const getCdnTransformationConfig = () => {
  const url = `${API_ENDPOINT}/common/getCdnTransformationConfig`;
  return request(url, getAPICallObject('GET'));
};

export const getS3UrlFileSizes = (data) => {
  const url = `${API_ENDPOINT}/assets/files/metadata`;
  return request(url, getAPICallObject('POST', data));
};

export const getTemplateInfoById = async ({
  id, username, oa_id, token, host,
}) => {
  const url = `${API_ENDPOINT}/templates/v1/${id}/Zalo?username=${username}&oa_id=${oa_id}&token=${token}&host=${host}`;
  const compressedTemplatesData = await request(url, getAPICallObject('GET'));
  const {response = ''} = compressedTemplatesData || {};
  return { ...compressedTemplatesData, response: decompressJsonObject(response)};
};

export const getMetaTags = ({previewUrl}) => {
  const url = `${API_ENDPOINT}/common/getMetaTags?url=${previewUrl}`;
  return request(url, getAPICallObject('GET'));
};

export const getSupportVideosConfig = () => {
  const url = `${ARYA_ENDPOINT}/support_videos/?product=Creatives`;
  return request(url, getAPICallObject('GET'));
};

export const getNavigationConfigApi = async () => {
  const url = `${ARYA_ENDPOINT}/navigations`;
  return request(url, getAPICallObject('GET'));
};

export const getLiquidTags = (content) => {
  const url = `${LIQUID_API_ENDPOINT}/extractTags`;
  return request(url, getAPICallObject("POST", { content }, false, true));
};

export const createCentralCommsMetaId = (payload, metaType = TRANSACTION) => {
  const url = `${API_ENDPOINT}/common/central-comms/meta-id/${metaType}`;
  return request(url, getAPICallObject('POST', payload, false, false, false, true));
};

export const updateMetaConfig = (payload, metaType = TRANSACTION, metaId) => {
  const url = `${API_ENDPOINT}/common/central-comms/meta-id/${metaType}/${metaId}`;
  return request(url, getAPICallObject('PATCH', payload, false, false, false, true));
};

// Customer Search APIs for Email Test & Preview Feature
export const searchCustomers = ({ query }) => {
  const url = `${MEMBERCARE_API_ENDPOINT}/customers/search?q=${encodeURIComponent(query)}&limit=10`;
  return request(url, getLoyaltyAPICallObject('GET'));
};

export const extractTagsWithMetaData = (payload) => {
  const url = `${LIQUID_API_ENDPOINT}/extractTagsWithMetaData`;
  return request(url, getAPICallObject('POST', payload, false, true));
};

export const updateEmailPreview = (payload) => {
  const url = `${LIQUID_API_ENDPOINT}/preview`;
  return request(url, getAPICallObject('POST', payload, false, true));
};

export const sendTestMessage = (payload) => {
  const url = `${LIQUID_API_ENDPOINT}/sendTestMessage`;
  return request(url, getAPICallObject('POST', payload, false, true));
};

export const fetchTestCustomers = () => {
  const url = `${IRIS_API_ENDPOINT}/userGroup/default`;
  return request(url, getAPICallObject('GET', null, false, true));
};

export const fetchTestGroups = () => {
  const url = `${IRIS_API_ENDPOINT}/userGroup?isDefault=false`;
  return request(url, getAPICallObject('GET', null, false, true));
};

export const getBulkCustomerDetails = (userIds) => {
  const user = loadItem('user');
  const url = `${ADIONA_API_ENDPOINT}/journeys/getBulkCustomer?source=ALL&userValue=${user?.loginName}`;
  return request(url, getLoyaltyAPICallObject('POST', userIds));
};

export const createTestMessageMeta = (payload) => {
  const url = `${LIQUID_API_ENDPOINT}/TEST/createMessageMeta`;
  return request(url, getAPICallObject('POST', payload, false, true));
};

export const updateTestMessageMeta = (payload) => {
  const url = `${LIQUID_API_ENDPOINT}/TEST/${payload.messageMetaConfigId}/updateMessageMeta`;
  return request(url, getAPICallObject('POST', payload?.data, false, true));
};

/**
 * P4.1: Get asset processing status for async uploads
 * @param {string} type - Asset type (image, video, document)
 * @param {string} assetId - Asset ID to check status
 * @returns {Promise} Promise resolving to asset status
 */
export const getAssetStatus = (type, assetId) => {
  const url = `${API_ENDPOINT}/assets/${type}/${assetId}/status`;
  return request(url, getAPICallObject('GET'));
};

export const getBeePopupBuilderToken = () => {
  const url = `${API_ENDPOINT}/common/getInappTokenData`;
  return request(url, getAPICallObject('GET'));
};

/**
 * Look up member by identifier (email or mobile) for add test customer flow.
 * Uses standard API auth headers (no x-cap-ct) to avoid CORS preflight issues with node layer.
 * @param {string} identifierType - 'email' or 'mobile'
 * @param {string} identifierValue - email address or mobile number
 * @returns {Promise} Promise resolving to { success, response: { exists, customerDetails } }
 */
export const getMembersLookup = (identifierType, identifierValue) => {
  const url = `${API_ENDPOINT}/members?identifierType=${encodeURIComponent(identifierType)}&identifierValue=${encodeURIComponent(identifierValue)}`;
  return request(url, getAPICallObject('GET'));
};

export const createTestCustomer = (payload) => {
  const url = `${API_ENDPOINT}/testCustomers`;
  return request(url, getAPICallObject('POST', payload));
};

export {request, getAPICallObject};
