import axios from "axios";
import * as crypto from "crypto";
import log from "../../config/log";
import CONSTANTS from "../../config/constants";

export const splitPayment = async (
  type: string,
  payuId: string,
  splitObj: any
) => {
  const U = "ClientPayout";
  const F = "splitPayment";

  const url = process.env.PAYU_SPLIT_URL || "";
  const key = process.env.PAYU_KEY || "";
  const command = "payment_split";
  const salt = process.env.PAYU_SALT;

  const var1 = JSON.stringify({
    type: type,
    payuId: payuId, // PayU Transaction Id
    splitInfo: splitObj,
  });

  const hashString = `${key}|${command}|${var1}|${salt}`;
  const sha512Hash = crypto
    .createHash("sha512")
    .update(hashString)
    .digest("hex");

  const data = new URLSearchParams({
    key,
    command,
    var1,
    hash: sha512Hash,
  });

  const sendRequest = async () => {
    try {
      const response = await axios.post(url, data.toString(), {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/x-www-form-urlencoded",
        },
      });

      return response.data;
    } catch (error: any) {
      log.error(
        `[${U}], [${F}], PayU Transaction ID [${payuId}], Split Object [${splitObj}], Type [${type}], Error in Split Payment: ${
          error?.message || error
        }`
      );
      return {
        msg: CONSTANTS.MSG.ERROR_MESSAGE,
        isSuccess: false,
        isServerError: true,
      };
    }
  };

  const response = await sendRequest();

  if (!response) {
    log.info(
      `[${U}], [${F}], PayU ID [${payuId}], No Response From Split Payment API `
    );
    return {
      msg: "Unable to split payment. Please try again later",
      isSuccess: false,
      isServerError: false,
    };
  }

  log.info(
    `[${U}], [${F}], PayU ID [${payuId}], Split Payment API Response: ${JSON.stringify(
      response
    )}`
  );

  return response;
};

export const releasePayment = async (payuId: string, mid: string) => {
  const U = "ClientPayout";
  const F = "releasePayment";

  const url = process.env.PAYU_SPLIT_URL || "";
  const key = process.env.PAYU_KEY || "";
  const command = "release_settlement";
  const salt = process.env.PAYU_SALT;
  const var1 = payuId; // PayU Transaction ID
  const var2 = mid; // Child MID

  const hashString = `${key}|${command}|${var1}|${salt}`;
  const sha512Hash = crypto
    .createHash("sha512")
    .update(hashString)
    .digest("hex");

  const data = new URLSearchParams({
    key: key,
    command: command,
    var1: var1,
    var2: var2,
    hash: sha512Hash,
  });

  const sendRequest = async () => {
    try {
      const response = await axios.post(url, data.toString(), {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/x-www-form-urlencoded",
        },
      });

      return response.data;
    } catch (error: any) {
      log.error(
        `[${U}], [${F}], PayU Transaction ID [${payuId}], MID [${mid}], Error in Release Payment: ${
          error?.message || error
        }`
      );
      return {
        msg: CONSTANTS.MSG.ERROR_MESSAGE,
        isSuccess: false,
        isServerError: true,
      };
    }
  };

  const response = await sendRequest();

  if (!response) {
    log.info(
      `[${U}], [${F}], PayU ID [${payuId}], No Response From Release Payment API `
    );
    return {
      msg: "Unable release payment. Please try again later",
      isSuccess: false,
      isServerError: false,
    };
  }

  log.info(
    `[${U}], [${F}], PayU ID [${payuId}], Release Payment API Response: ${JSON.stringify(
      response
    )}`
  );

  return response;
};

export const getSplitPaymentDetails = async (
  payuId: string
) => {
  const U = "ClientPayout";
  const F = "getSplitPaymentDetails";

  const url = process.env.PAYU_SPLIT_URL || "";
  const key = process.env.PAYU_KEY || "";
  const command = "aggregator_check_action_status_txnid";
  const salt = process.env.PAYU_SALT;

  const var1 = payuId;

  const hashString = `${key}|${command}|${var1}|${salt}`;
  const sha512Hash = crypto
    .createHash("sha512")
    .update(hashString)
    .digest("hex");

  const data = new URLSearchParams({
    key,
    command,
    var1,
    hash: sha512Hash,
  });

  const sendRequest = async () => {
    try {
      const response = await axios.post(url, data.toString(), {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/x-www-form-urlencoded",
        },
      });

      return response.data;
    } catch (error: any) {
      log.error(
        `[${U}], [${F}], PayU Transaction ID [${payuId}], Error in Getting Split Payment Details: ${
          error?.message || error
        }`
      );
      return {
        msg: CONSTANTS.MSG.ERROR_MESSAGE,
        isSuccess: false,
        isServerError: true,
      };
    }
  };

  const response = await sendRequest();

  if (!response) {
    log.info(
      `[${U}], [${F}], PayU ID [${payuId}], No Response From Split Payment API `
    );
    return {
      msg: "Unable to split payment. Please try again later",
      isSuccess: false,
      isServerError: false,
    };
  }

  log.info(
    `[${U}], [${F}], PayU ID [${payuId}], Split Payment API Response: ${JSON.stringify(
      response
    )}`
  );

  return response;
};
