import axios from 'axios';
import { HttpException, HttpStatus } from '@nestjs/common';
import {
  saleForceClientId,
  saleForceClientSecret,
  saleForcePassword,
  saleForceTokenUrl,
  saleForceUsername,
} from '../config/common';

/**
 * Sends a POST request to the Salesforce API to get an auth token.
 *
 * @returns {Promise<string>} - A promise that resolves to the auth token from the Salesforce API.
 * @throws {HttpException} - Throws an exception if the request fails.
 */
async function getSFAuthToken(): Promise<string> {
  try {
    const form = new FormData();
    form.append('grant_type', 'password');
    form.append('client_id', saleForceClientId);
    form.append('client_secret', saleForceClientSecret);
    form.append('username', saleForceUsername);
    form.append('password', saleForcePassword);

    const options = {
      method: 'POST',
      url: saleForceTokenUrl,
      headers: {
        Cookie:
          'BrowserId=6uX_j0NtEeuIIFWM7XVugQ; BrowserId=2NSdI90JEe2k8FsoDH-mow; CookieConsentPolicy=0:0; LSKey-c$CookieConsentPolicy=0:0',
        'content-type':
          'multipart/form-data; boundary=---011000010111000001101001',
      },
      data: form,
    };

    const response = await axios.request(options);
    if (response.status >= 200 && response.status < 300) {
      return response.data.access_token;
    } else {
      throw new Error(
        `Request failed while accessing the access token  with  status code  ${response.status}`,
      );
    }
  } catch (error) {
    throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
  }
}

export default getSFAuthToken;
