const { fetchContacts } = require("../services/apiService");
const { sendAlertToUser } = require("../services/webSocket")

const fieldTitleMap = {
  Hq5fePgYMo1lfrJeSXkr: "call_frequency",
  QL0rzaEwmJaEk9jdYMs9: "greeting_script",
  upW8g15t9YnYiWlnaBpr: "primary_caregiver_phone",
  gdsuDxKmmudOEDk3FiQX: "call_active",
  "3U3ZJgLL1rpJJroD0Az7": "question_1_type",
  iCdzNGVcI9TXCMZB9VAA: "call_priority",
  Q0tV2XVHkCCp3oYCc1uG: "closing_script",
  lC7wcDZ1iwVMuVvCBKrQ: "voice_gender",
  GAw9gU6eHmJCmVqpmrf3: "retry_max",
  "24kfk9oSCFzPh2ebpyUl": "emergency_contact_name",
  cikiuNK65qNw4V5Gy4TR: "call_time",
  J3fWeliXkIMuYnkKk2yt: "voice_style",
  u7WmIttXGLrmvGqnT9CH: "contact_type",
  eEc7gSzB3fmqahLlr9xX: "retry_interval",
  wZwE35nLUt4ofApaJSLk: "emergency_contact_phone",
  LYZXV61lONvQF3SoM95G: "primary_caregiver_name",
  "635VPvmnotbVwZOXMGf8": "primary_caregiver_email",
  v6iwpMuopjEfPWBLMXEN: "secondary_caregiver_name",
  sPa3DwpIM6z5tDSfWxwf: "question_1_alert_on",
  RrJXvwDnybenFmd31BnM: "secondary_caregiver_phone",
  mbqkQQaYyAovaxHfgWz0: "secondary_caregiver_email",
  cEnullg0BPqHvcbRLYKz: "escalation_order",
  qY4kgf4j8qxbLrWJPDqJ: "question_2",
  Ft47Zo8DdD3U0ZJw6dS3: "question_2_type",
  "7eXeyWZwLg7f55NJdOUI": "question_2_alert_on",
  kpyhzADdBf2WSfAL3X5M: "How r you",
};

async function getUserData(req, res) {

  const { userId, token } = req.body || {};

  if (!userId || !token) {
    return res.status(400).json({ error: "Missing userId or token" });
  }

  try {
    const allContacts = await fetchContacts();

    const filteredContacts = allContacts.contacts
      .filter((contact) => contact.assignedTo === userId)
      .map((contact) => {
        // Map customField array to fields object with mapped keys
        const mappedFields = {};

        (contact.customField || []).forEach(({ id, value }) => {
          const mappedKey = fieldTitleMap[id] || id;
          mappedFields[mappedKey] = value;
        });

        return {
          ...contact,
          fields: mappedFields,
          customField: undefined, // or delete contact.customField to omit
        };
      });

    return res.json({ filteredContacts });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
}

async function getNotifications(req,res){
  if(req.body){

    console.log("req body---",req.body)
    sendAlertToUser(req.body.userId,req.body.alert)
    return res.status(200).json({ message : "sent alert !!" });
  }
  else{
    return res.status(403).json({ message : "Please send notifications!!" });
  }



}

module.exports = { getUserData ,getNotifications};