const axios = require('axios');
const config = require('../config/config.json');
const { decrypt } = require('./encryptionService');

async function fetchContacts() {
  try {
    const decryptedApiKey = decrypt(config.encryptedApiKey);
    const response = await axios.get('https://rest.gohighlevel.com/v1/contacts/', {
      headers: {
        Authorization: `Bearer ${decryptedApiKey}`
      }
    });
    return response.data;
  } catch (error) {
    throw new Error(`API Error: ${error.message}`);
  }
}

async function fetchCallList({ assignedTo, call_id }) {

  try {
    if (!assignedTo && !call_id) {
      throw new Error('Either assignedTo or call_id must be provided.');
    }

    const decryptedApiKey = decrypt(config.encryptedApiKey_callList);

    const axiosConfig = {
      method: 'post',
      maxBodyLength: Infinity,
      url: 'https://api.retellai.com/v2/list-calls',
      headers: { 
        'Authorization': `Bearer ${decryptedApiKey}`, 
        'Content-Type': 'application/json'
      },
      data: {} // Include any required data here
    };

    const response = await axios.request(axiosConfig);

    // Adjust the path to the data based on the actual response structure
    const calls = response.data.calls || response.data; // Replace 'calls' with the correct property if different

    let filteredCalls = [];

    if (assignedTo) {
      filteredCalls = calls.filter(call => 
        String(call.retell_llm_dynamic_variables?.assignedTo) === String(assignedTo)
      );
    } else if (call_id) {
      filteredCalls = calls.filter(call => 
        String(call.call_id) === String(call_id)
      );
    }

    return filteredCalls;
  } catch (error) {
    throw new Error(`API Error: ${error.message}`);
  }
}




module.exports = { fetchContacts, fetchCallList };
