const axios = require("axios");

let accessToken = null;
let tokenExpiry = null;

/**
 * Generate new token from Travelport
 */
const generateToken = async () => {
  console.log("Generating new Travelport token...");

  const response = await axios.post(
    process.env.TRAVELPORT_AUTH_URL,
    new URLSearchParams({
      grant_type: process.env.TRAVELPORT_GRANT_TYPE,
      username: process.env.TRAVELPORT_USERNAME,
      password: process.env.TRAVELPORT_PASSWORD,
      client_id: process.env.TRAVELPORT_CLIENT_ID,
      client_secret: process.env.TRAVELPORT_CLIENT_SECRET,
    }),
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cache-Control": "no-cache",
      },
    }
  );

  accessToken = response.data.access_token;

  // expiry time in milliseconds
  tokenExpiry = Date.now() + (response.data.expires_in - 300) * 1000;

  console.log("Travelport token generated successfully");
  console.log(
  "[TOKEN SERVICE] NEW TOKEN:",
  accessToken
);

console.log(
  "[TOKEN SERVICE] TOKEN EXPIRY:",
  new Date(tokenExpiry)
);

  return accessToken;
};

/**
 * Return valid token
 */
// const getToken = async () => {
//   // If token exists and not expired
//   if (accessToken && tokenExpiry && Date.now() < tokenExpiry) {
//     console.log("Using existing Travelport token");
//     return accessToken;
//   }

//   // Generate new token
//   return await generateToken();
// };

// module.exports = {
//   getToken,
// };
const getToken = async () => {

  // Token exists and valid
  if (
    accessToken &&
    tokenExpiry &&
    Date.now() < tokenExpiry
  ) {

    console.log(
      "\n[TOKEN SERVICE] USING EXISTING TOKEN"
    );

    console.log(
      "[TOKEN SERVICE] TOKEN:",
      accessToken
    );

    console.log(
      "[TOKEN SERVICE] TOKEN EXPIRY:",
      new Date(tokenExpiry)
    );

    return accessToken;
  }

  // Generate new token
  return await generateToken();
};
module.exports = {
  getToken,
};




