// telegram/handlers/friendsHandler.js
const shared_consts = require('../../tools/shared_nodejs');
const tools = require('../../tools/general');
const { User } = require('../../models/user');
const printf = require('util').format;
const { handleRegistration, InlineConferma } = require('./registrationHandler');

async function handleFriends({ bot, cl, idapp, msg, data, user, userDest, username_action }) {
  let notifyText = '';

  // SI -> amicizia
  if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
    if (userDest) {
      const req = tools.getReqByPar(idapp, username_action);
      const already = await User.isMyFriend(idapp, data.username, data.userDest);
      if (!already) await User.setFriendsCmd(req, idapp, data.username, data.userDest, shared_consts.FRIENDSCMD.SETFRIEND);
      await cl.sendMsg(msg.chat.id, '🤝 Amicizia confermata!');
      notifyText = 'Amicizia OK';
    }
    return notifyText;
  }

  // NO -> amicizia (rimuovi/nega)
  if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
    if (userDest) {
      const req = tools.getReqByPar(idapp, username_action);
      const ris = await User.setFriendsCmd(req, idapp, data.username, data.userDest, shared_consts.FRIENDSCMD.REMOVE_FROM_MYFRIENDS);
      if (ris) {
        const msgDest = printf(tools.gettranslate('MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED', user.lang), data.username);
        await localSendMsgByUsername(idapp, data.userDest, msgDest);
      }
      await cl.sendMsg(msg.chat.id, '🚫 Amicizia rifiutata.');
      notifyText = 'Rifiutata';
    }
    return notifyText;
  }

  // SI -> handshake
  if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
    if (userDest) {
      const req = tools.getReqByPar(idapp, username_action);
      const already = await User.isMyHandShake(idapp, data.userDest, data.username);
      if (!already) await User.setFriendsCmd(req, idapp, data.userDest, data.username, shared_consts.FRIENDSCMD.SETHANDSHAKE);
      await cl.sendMsg(msg.chat.id, '🤝 Handshake confermato!');
      notifyText = 'Handshake OK';
    }
    return notifyText;
  }

  return 'OK';
}

// helper locale (equivalente del tuo local_sendMsgTelegram)
async function localSendMsgByUsername(idapp, username, text) {
  const teleg_id = await User.TelegIdByUsername(idapp, username);
  const cl = require('../telegram.bot.init').getclTelegByidapp(idapp);
  if (cl && teleg_id) return await cl.sendMsg(teleg_id, text);
  return null;
}

module.exports = { handleFriends };
