import { HttpException, HttpStatus } from '@nestjs/common';
import axios from 'axios';
import getSFAuthToken from './get-sf-auth-token';
// import logger from '../../src/logger/mtLogger';

export type HttpAcknowledgement = {
  status: number;
  data: { id: string };
};

async function sendHttpRequestAxios(
  options: {
    method: string;
    url: string;
    headers?: any;
    data: any;
  },
  returnBody: boolean = false,
): Promise<number | HttpAcknowledgement> {
  try {
    if (!options.headers) {
      const token = await getSFAuthToken();
      options.headers = {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      };
    }

    // Log the payload for 3rd party integration including Salesforce reverse integration
    // logger.info(
    //   'Payload for 3rd party integration including Salesforce reverse integration',
    //   {
    //     statusCode: 500,
    //     timestamp: new Date().toISOString(),
    //     path: 'sendHttpRequestAxios',
    //     message: JSON.stringify(options),
    //   },
    // );

    const response = await axios(options);

    if (response.status >= 200 && response.status < 300) {
      if (returnBody) {
        return { status: response.status, data: response.data };
      }
      return response.status;
    } else {
      throw new Error(
        `Request failed with status code ${response.status} ${response}`,
      );
    }
  } catch (error) {
    if (error.response && returnBody) {
      return { status: error.response.status, data: error.response.data };
    }
    let errorMessage = error.message;
    if (Array.isArray(error.response.data)) {
      errorMessage = error.response.data
        .map((err) => {
          const message = err.message || 'No message';
          const errorCode = err.errorCode || 'No error code';
          const fields =
            err.fields && err.fields.length > 0
              ? err.fields.join(', ')
              : 'No fields';
          return `Error message: ${message}, Error code: ${errorCode}, Fields: ${fields}`;
        })
        .join('; ');
    } else if (error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message;
    }
    // throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    throw new HttpException(
      errorMessage,
      error.response?.status || HttpStatus.BAD_REQUEST,
      error.response.statusText,
    );
  }
}
export { sendHttpRequestAxios };
