const usersModel = require("../model/userModel");




const storeCallLog = async (req, res) => {
  const data = req.body;

  if (!data.uuid || !data.call_to_number || !data.caller_id_number) {
    return res.status(400).json({ message: "Missing required parameters" });
  }

  try {
    await usersModel.saveCallLog(data);
    return res.status(200).json({ message: "Call log stored successfully" });
  } catch (error) {
    console.error("Error processing the request:", error);
    return res.status(500).json({  success: false, message: 'Server error storing call log.'  });
    
  }
};





// const handleCallRequest = async (req, res) => {
//   const { uuid, call_id, call_to_number, caller_id_number, start_stamp } = req.body;

//   if (!uuid || !call_id || !call_to_number || !caller_id_number || !start_stamp) {
//     return res.status(400).json({ message: "Missing required parameters" });
//   }

//   console.log("caller_id_number:", caller_id_number);
//   console.log("call_to_number:", call_to_number);

//   try {
//     // Get the latest call log for the customer from DB
//     const result = await usersModel.getLastAgentByCustomer(caller_id_number, call_to_number);

//     if (!result || result.length === 0) {
//       return res.status(404).json({ message: "No agent found for this customer" });
//     }

//     const fullJsonStr = result.full_json;

//     let parsed;
//     try {
//       parsed = JSON.parse(fullJsonStr);
//     } catch (e) {
//       console.error("Failed to parse full_json:", e);
//       return res.status(500).json({ message: "Invalid JSON data in DB" });
//     }

//     let agentNumber = null;

//     if (parsed.answered_agent && parsed.answered_agent.agent_number) {
//       agentNumber = parsed.answered_agent.agent_number.replace(/^\+91/, '');
//     } else if (
//       Array.isArray(parsed.missed_agent) &&
//       parsed.missed_agent.length > 0 &&
//       parsed.missed_agent[0].agent_number
//     ) {
//       agentNumber = parsed.missed_agent[0].agent_number.replace(/^\+91/, '');
//     }

//     if (!agentNumber) {
//       return res.status(404).json({ message: "Agent number not found in call record" });
//     }

//     const transferData = {
//       transfer: {
//         type: "number",
//         data: [agentNumber],
//       },
//     };

//     return res.status(200).json(transferData);

//   } catch (error) {
//     console.error("Error processing call request:", error);
//     return res.status(500).json({ message: "Internal Server Error" });
//   }
// };

const handleCallRequest = async (req, res) => {
  const { uuid, call_id, call_to_number, caller_id_number, start_stamp } = req.body;
  const logs = req.body;
  // console.log("body:", req.body);
  try {
    const callLog = await usersModel.saveDialerCallLog(logs);

    if (!callLog) {
      return res.status(500).json({ message: "Failed to save call" });
    }
  } catch (error) {
    console.error("Error processing call request:", error);
    return res.status(500).json({ message: "Internal Server Error" });
    
  }

  if (!uuid || !call_id || !call_to_number || !caller_id_number || !start_stamp) {
    return res.status(400).json({ message: "Missing required parameters" });
  }

  // console.log("caller_id_number:", caller_id_number);
  // console.log("call_to_number:", call_to_number);

  try {
    // Get the latest call log for the customer from DB
    const result = await usersModel.getLastAgentByCustomer(caller_id_number, call_to_number);

    if (!result || result.length === 0) {
      return res.status(404).json({ message: "No agent found for this customer" });
    }

    const fullJsonStr = result.full_json;

    let parsed;
    try {
      parsed = JSON.parse(fullJsonStr);
    } catch (e) {
      console.error("Failed to parse full_json:", e);
      return res.status(500).json({ message: "Invalid JSON data in DB" });
    }

    let agentNumber = null;

    if (parsed.answered_agent && parsed.answered_agent.agent_number) {
      agentNumber = parsed.answered_agent.agent_number.replace(/^\+91/, '');
    } else if (
      Array.isArray(parsed.missed_agent) &&
      parsed.missed_agent.length > 0 &&
      parsed.missed_agent[0].agent_number
    ) {
      agentNumber = parsed.missed_agent[0].agent_number.replace(/^\+91/, '');
    }

    if (!agentNumber) {
      return res.status(404).json({ message: "Agent number not found in call record" });
    }

    const transferData = {
      transfer: {
        type: "number",
        data: [agentNumber],
      },
    };

    return res.status(200).json(transferData);

  } catch (error) {
    console.error("Error processing call request:", error);
    return res.status(500).json({ message: "Internal Server Error" });
  }
};





module.exports = { handleCallRequest, storeCallLog };