const axios = require("axios");
const logger = require("../util/logger");

function computeDistance(origin, destination) {
  return new Promise((resolve, reject) => {
    const apiKey = "AIzaSyCOh0Fhlg8WjA9-iVL1pl7hCweo17fH7xg";
    const endpoint = "https://maps.googleapis.com/maps/api/directions/json";

    const params = {
      origin,
      destination,
      mode: "driving",
      key: apiKey,
    };

    const requestUrl = `${endpoint}?${new URLSearchParams(params).toString()}`;
    console.log(requestUrl);
    axios
      .get(requestUrl)
      .then((response) => {
        if (response.data.status === "ZERO_RESULTS") {
          logger.error(`GOOGLE API ERROR: ${JSON.stringify(response.data)}`);
          resolve(0);
          return;
        }

        if (
          !response.data.routes ||
          !response.data.routes[0] ||
          !response.data.routes[0].legs ||
          !response.data.routes[0].legs[0]
        ) {
          logger.error(`GOOGLE API ERROR: ${JSON.stringify(response.data)}`);
          resolve(0);
          return;
        }

        const distance = response.data.routes[0].legs[0].distance.value / 1000; // km
        resolve(distance);
      })
      .catch((error) => {
        logger.error(`GOOGLE API ERROR: ${error}`);
        console.error("Error fetching distance:", error.message);
        reject(error);
      });
  });
}

module.exports = computeDistance;
