import axios from "axios";
import qs from "querystring";
import log from "../../config/log";
import CONSTANTS from "../../config/constants";
import moment from "moment";

export const getClientToken = async () => {
  const U = "getClientToken";

  const hubBaseUrl = "https://accounts.payu.in";
  const clientId =
    "be348c99be1b7d27868c4bf81e62cf02f0288349eba6cd03ca3d7db6aa4e0fea";
  const clientSecret =
    "d61fb574e70fad67ae5a3f823b5564c5473892056f0d7c0757b7f515742f4487";

  const url = `${hubBaseUrl}/oauth/token`;

  const data = {
    client_id: clientId,
    client_secret: clientSecret,
    grant_type: "client_credentials",
    scope: "create_payment_links",
  };

  const headers = {
    "Content-Type": "application/x-www-form-urlencoded",
  };

  const generateClientToken = async () => {
    try {
      const response = await axios.post(url, qs.stringify(data), { headers });
      log.info(
        `[${U}], PayU Client Token Genreation API Response [${JSON.stringify(
          response.data
        )}]`
      );
      return response.data;
    } catch (error: any) {
      log.error(
        `[${U}], Error in PayU Client Token Genreation API [${
          error?.message || error
        }]`
      );
      return {
        msg: CONSTANTS.MSG.ERROR_MESSAGE,
        isSuccess: false,
        isServerError: true,
        data: null,
      };
    }
  };

  const response = await generateClientToken();

  if (!response) {
    log.info(`[${U}], No Response From PayU Client Token Genreation API `);
    return {
      msg: "Unable to generate client token. Please try again later",
      isSuccess: false,
      isServerError: true,
      data: null,
    };
  } else if (response.access_token) {
    return {
      data: response,
      isSuccess: true,
    };
  } else {
    log.info(
      `[${U}], PayU Client Token Genreation API Response [${JSON.stringify(
        response
      )}], Did not receive access token`
    );
    return {
      msg: "Unable to generate client token. Please try again later",
      isSuccess: false,
      isServerError: true,
      data: response,
    };
  }
};

export const createPaymentLink = async (
  amount: number,
  invoice: string,
  description: string,
  tenantName: string,
  tenantMobile: string,
  clientName: string,
  clientMobile: string,
  gidTenantId: string,
  dueId: number,
  ledgerReferenceId: string
) => {
  const C = "Client Controller";
  const F = "UpdateTenantLastReminded";
  const U = "createPaymentLink";

  const clientTokenResponse = await getClientToken();
  if (!clientTokenResponse.isSuccess) {
    log.info(`[${C}], [${F}], [${U}], Error From Client Token Generation API`);
    return {
      msg: "Unable to generate client token. Please try again later",
      isSuccess: false,
      isServerError: true,
      data: clientTokenResponse.data || "",
    };
  }

  const url = "https://oneapi.payu.in/payment-links";
  const merchantId = "12629916";
  const accessToken = clientTokenResponse.data.access_token;

  const headers = {
    merchantId: merchantId,
    "Content-Type": "application/json",
    Authorization: `Bearer ${accessToken}`,
  };

  const data = {
    invoiceNumber: invoice,
    subAmount: amount,
    expiryDate: moment().add(5, "days").format("YYYY-MM-DD HH:mm:ss"),
    isAmountFilledByCustomer: false,
    isPartialPaymentAllowed: false,
    description: description,
    source: "API",
    enforcePayMethod: "upi",
    customer: {
      name: tenantName,
      phone: tenantMobile,
    },
    udf: {
      udf1: clientName,
      udf2: clientMobile,
      udf3: gidTenantId,
      udf4: dueId,
      udf5: ledgerReferenceId,
    },
  };

  log.info(`Header [${JSON.stringify(headers)}], Data [${JSON.stringify(data)}]`);

  const generateLink = async () => {
    try {
      const response = await axios.post(url, data, { headers });
      log.info(
        `[${U}], PayU Client Link Genreation API Response [${JSON.stringify(
          response.data
        )}]`
      );
      return response.data;
    } catch (error: any) {
      log.error(
        `[${U}], Error in PayU Client Link Genreation API [${
          error?.message || error
        }]`
      );
      return {
        msg: CONSTANTS.MSG.ERROR_MESSAGE,
        isSuccess: false,
        isServerError: true,
        data: null,
      };
    }
  };

  const response = await generateLink();

  if (!response) {
    log.info(`[${U}], No Response From PayU Payment Link Generation API `);
    return {
      msg: "Unable to generate payment link. Please try again later",
      isSuccess: false,
      isServerError: true,
      data: null,
    };
  } else if (response.status === 0) {
    return {
      data: response,
      isSuccess: true,
    };
  } else {
    log.info(
      `[${U}], Response [${JSON.stringify(
        response
      )}], Error in PayU Payment Link Genreation API,`
    );
    return {
      msg: "Unable to generate client token. Please try again later",
      isSuccess: false,
      isServerError: true,
      data: response || "",
    };
  }
};
