const db = require('../config/dbConnect');


// const getLastAgentByCustomer = (customer_number) => {
//   return new Promise((resolve, reject) => {
//     const query = `
//       SELECT full_json 
//       FROM agent_call_logs 
//       WHERE customer_number = ? 
//         AND direction = 'clicktocall'
//       ORDER BY start_stamp DESC 
//       LIMIT 1
//     `;

//     db.query(query, [customer_number], (err, results) => {
//       if (err) return reject(err);
//       resolve(results.length ? results[0] : null); // results[0] is your row
//     });
//   });
// };

const getLastAgentByCustomer = (caller_id_number, call_to_number) => {
  return new Promise((resolve, reject) => {
    const query = `
      SELECT full_json 
      FROM agent_call_logs 
      WHERE (caller_id_number = ? OR call_to_number = ?) 
        AND direction = 'clicktocall'
      ORDER BY start_stamp DESC 
      LIMIT 1
    `;

    db.query(query, [caller_id_number, call_to_number], (err, results) => {
      if (err) {
        console.error("❌ SQL Error:", err);
        return reject(err);
      }
      
      // console.log("🔍 Query Result:", results);
      resolve(results.length ? results[0] : null);
    });
  });
};


const saveCallLog = async (data) => {
  const customer_number = data.call_to_number?.startsWith('+')
    ? data.call_to_number
    : '+' + data.call_to_number;

    console.log('customer_number', customer_number);

  const sql = `
    INSERT INTO agent_call_logs (
      uuid, call_id, call_to_number, caller_id_number, start_stamp,
      answer_stamp, end_stamp, hangup_cause, duration, billsec,
      agent_id, agent_name, agent_number, did_number, customer_number,
      direction, call_status, reason_key, recording_url, full_json
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  const values = [
    data.uuid,
    data.call_id,
    customer_number,
    data.caller_id_number,
    data.start_stamp,
    data.answer_stamp,
    data.end_stamp,
    data.hangup_cause,
    parseInt(data.duration) || 0,
    parseInt(data.billsec) || 0,
    data.answered_agent?.id || null,
    data.answered_agent_name || null,
    data.answered_agent_number || null,
    data.caller_id_number,
    customer_number,
    data.direction,
    data.call_status,
    data.reason_key,
    data.recording_url,
    JSON.stringify(data)
  ];

  return await db.query(sql, values);
};


const saveDialerCallLog = async (data) => {
  const sql = `INSERT INTO dialercallog (json, created_at) VALUES (?, ?);`;
  const values = [JSON.stringify(data), new Date()];
  return await db.query(sql, values);
}


module.exports = { getLastAgentByCustomer, saveCallLog, saveDialerCallLog };