/**
 * Data fetching methods for MenuUtils.
 * Handles primary/fallback URL fetching and API calls.
 */

const dataFetching = {
  async fetchData(url, fallbackUrl) {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      const responsData =  await response.json();
      //responsData
      const data = responsData.data;
      /* .map(item => {
        const { vendor_name, ...rest } = item;
        return {
        name: vendor_name,
        ...rest
        };
      }); */
      console.log(url);
      console.log("Response Data: ", data);
      return data;

    } catch (err) {
      console.warn(
        `Primary URL failed: ${url}. Trying fallback URL: ${fallbackUrl}`,
        err
      );
      try {
        const response = await fetch(fallbackUrl);
        if (!response.ok)
          throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
      } catch (fallbackErr) {
        console.error("Both primary and fallback URLs failed:", fallbackErr);
        return [];
      }
    }
  },

  async fetchProjectData(url) {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      const responsData =  await response.json();
      console.log("Response Data: ", responsData);
      return responsData;

    } catch (err) {
      /* intentionally empty */
    }
  },

  // Save changes to API
  async apiCall(node) {
    try{
        // OLFIANT when a browser refreshes the tag code is lost!!! fix this later!!!!!
        // FIX UUID ALSO LATER

        if(node.assetTagCode !== "" || node.assetTagCode !== null){ /* intentionally empty */ }
        // API call to register or check asset in central database
          let assetregisterAPI = node.configUrls.cloud.taggcodeAPI + "/asset/create_asset.php";

          const assetModelId = node.modelMetadata.id; //asset_product_model_id
          const uuid = node.uuid; //asset_product_model_uuid
          const assetName =  node.assetType; //asset_name / type?
          const description = node.name; // asset_description
          const assetStatus = "actief"; //asset_status -> koppel aan enable / disable node ? or make dropdown ?
          const assetProfileId = 1; //asset_profile_id  these are the rules to check if the childs are valid under this node (parent / child id?)
          const child_assets = ["63247"]; //child_assets tagnummer of id?
          const assetProcessId = node.processId; //asset_process_id
          const assetLocationId = node.locationId; //asset_location_id
          const tagCode = node.assetTagCode; // if already exists in the node information use it to tell the api it exists and it will update else we will get it from the api call
          //console.log(`this is my tagCode: ${tagCode}`);

          // Build base URL with required parameters
          let apiUrl = `?asset_product_model_id=${assetModelId}&asset_product_model_uuid=${uuid}&asset_name=${assetName}&asset_description=${description}&asset_status=${assetStatus}&asset_profile_id=${assetProfileId}&asset_location_id=${assetLocationId}&asset_process_id=${assetProcessId}&child_assets=${child_assets}`;

          // Only add tagCode to URL if it exists
          if (tagCode) {
              apiUrl += `&asset_tag_number=${tagCode}`;
              console.log('hello there');
          }

          assetregisterAPI += apiUrl;
          console.log("API call to register asset in central database", assetregisterAPI);

          const response = await fetch(assetregisterAPI, {
              method: "POST"
          });

          // Get the response text first
          const responseText = await response.text();
          console.log("Raw API response:", responseText);

          // Try to parse the JSON, handling potential parsing errors
          let jsonResponse;
          try {
              jsonResponse = JSON.parse(responseText);
          } catch (parseError) {
              console.error("JSON Parsing Error:", parseError);
              console.error("Response that could not be parsed:", responseText);
              throw new Error("Failed to parse API response");
          }

          console.log(jsonResponse);

          if(jsonResponse.success){
              console.log(`${jsonResponse.message}, tag number: ${jsonResponse.asset_tag_number}, asset id: ${jsonResponse.asset_id}`);
              // Save the asset tag number and id to the node
          } else {
              console.log("Asset not registered in central database");
          }
          return jsonResponse;

      } catch (error) {
          console.log("Error saving changes to asset register API", error);
      }
  },
};

module.exports = dataFetching;
