import axios from "axios";

import { createQueryString } from "../utils/helperMethods";
import { getUrl } from "./apiConfig";

export const TLogEvent = (
  dispatch,
  getState,
  type,
  baseUrl,
  urlParams = {},
  params = {},
  onSuccess,
  onFail,
  totalLogFlag = false
) => {
  const httpHeader = getState().common.httpHeader;
  const appStatus = getState().common.appStatus;
  const AUTHORIZATION = { headers: { ...httpHeader } };

  const {
    cntry_cd: cntryCd,
    plat_cd: platCd,
    prod_cd: prodCd,
    lang_cd: deviceLang,
    app_ver: appVersion,
  } = httpHeader;
  const { deviceId: dvcId } = appStatus;
  const deviceEulaFlag = httpHeader["X-Device-Eula"];
  const salesModelCode = httpHeader["X-Device-Model"];
  const dvcTp = "tv";

  if (typeof window === "object") {
    let url = Array.isArray(baseUrl)
      ? getUrl(getState, baseUrl[0])
      : getUrl(getState, baseUrl);

    if (!url) {
      return;
    }

    if (type === "get") {
      const _urlparams = createQueryString(urlParams);
      url += _urlparams ? `?${_urlparams}` : "";
    }

    let model;
    if (totalLogFlag) {
      model = {
        ...params,
        countryCode: cntryCd,
        deviceId: dvcId,
        devicePlatformVersion: dvcTp,
        platformCode: platCd,
        platformVersion: prodCd,
        appVersion,
        deviceEulaFlag,
        salesModelCode,
        deviceLang,
      };
    } else {
      model = {
        ...params,
        cntryCd,
        dvcId,
        dvcTp,
        platCd,
        prodCd,
      };
    }
    let axiosInstance;

    switch (type) {
      case "get":
        axiosInstance = axios.get(url, AUTHORIZATION);
        break;
      case "post":
        axiosInstance = axios.post(url, model, AUTHORIZATION);

        break;
    }

    if (axiosInstance) {
      axiosInstance
        .then((res) => {
          if (onSuccess) {
            onSuccess(res);
          }
        })
        .catch((error) => {
          const errorMessage = error && error.message ? error.message : '';
          const requestUrl = error.config && error.config.url ? error.config.url : '';
          
          // /lgsp/v1/log/recommend.lge 엔드포인트의 XML 오류만 무시
          if ((errorMessage.includes('XML') || 
               errorMessage.includes('요소 없음') ||
               errorMessage.includes('element')) &&
              requestUrl.includes('/lgsp/v1/log/recommend.lge')) {
            console.log('[TLogEvent] XML parsing error ignored for recommend endpoint');
            return; // recommend 엔드포인트의 XML 오류만 무시
          }
          
          // 다른 엔드포인트의 오류는 정상 처리
          if (onFail) {
            onFail(error);
          }
        });
    }
  }
};
