// telegram/handlers/callbackHandler.js
const tools = require('../../tools/general');
const shared_consts = require('../../tools/shared_nodejs');
const { User } = require('../../models/user');
const { Circuit } = require('../../models/circuit');
const { handleRegistration } = require('./registrationHandler');
const { handleFriends } = require('./friendsHandler');
const { handleCircuit } = require('./circuitHandler');
const { handleZoom } = require('./zoomHandler');
const { handlePassword } = require('./passwordHandler');

async function handleCallback(bot, cl, callbackQuery) {
  const idapp = cl.idapp;
  let notifyText = ''; // testo di notifica Telegram (answerCallbackQuery)
  try {
    // parsing payload dal tuo formato originale (action|username|userDest|groupId|circuitId|groupname)
    let data = {
      action: '',
      username: '',
      userDest: '',
      groupId: '',
      circuitId: '',
      groupname: '',
    };

    const raw = callbackQuery?.data || '';
    if (raw) {
      const arr = raw.split(tools.SEP);
      data = {
        action: arr[0] || '',
        username: arr[1] || '',
        userDest: arr[2] || '',
        groupId: arr[3] || '',
        circuitId: arr[4] || '',
        groupname: arr[5] || '',
      };
    }

    // normalizza username reali (come nel sorgente)
    data.username = await User.getRealUsernameByUsername(idapp, data.username);
    data.userDest = data.userDest ? await User.getRealUsernameByUsername(idapp, data.userDest) : '';

    const msg = callbackQuery.message;
    const opts = { chat_id: msg.chat.id, message_id: msg.message_id };

    // contest utente corrente
    await cl.setInit?.(msg); // se presente nel tuo codice
    const rec = cl.getRecInMem?.(msg);
    const username_action = rec?.user ? rec.user.username : '';

    // carica user e userDest compatti (come nel tuo codice)
    const user = data.username ? await User.getUserShortDataByUsername(idapp, data.username) : null;
    const userDest = data.userDest ? await User.getUserShortDataByUsername(idapp, data.userDest) : null;

    // routing per ambito
    const act = data.action || '';

    // 1) REGISTRAZIONE e varianti
    if (act.includes(shared_consts.CallFunz.REGISTRATION)) {
      notifyText = await handleRegistration({ bot, cl, idapp, msg, data, user, userDest, username_action });
    }
    // 2) AMICIZIA / HANDSHAKE
    else if (
      act.includes(shared_consts.CallFunz.RICHIESTA_AMICIZIA) ||
      act.includes(shared_consts.CallFunz.RICHIESTA_HANDSHAKE)
    ) {
      notifyText = await handleFriends({ bot, cl, idapp, msg, data, user, userDest, username_action });
    }
    // 3) CIRCUITI (aggiunta/rimozione)
    else if (
      act.includes(shared_consts.CallFunz.ADDUSERTOCIRCUIT) ||
      act.includes(shared_consts.CallFunz.REMUSERFROMCIRCUIT)
    ) {
      notifyText = await handleCircuit({ bot, cl, idapp, msg, data, user, userDest, username_action });
    }
    // 4) ZOOM (registrazione/presenze)
    else if (act.includes(shared_consts.CallFunz.REGISTRATION_TOZOOM) || act.includes('ZOOM')) {
      notifyText = await handleZoom({ bot, cl, idapp, msg, data, user, userDest, username_action });
    }
    // 5) RESET PASSWORD
    else if (act.includes(shared_consts.CallFunz.RESET_PWD)) {
      notifyText = await handlePassword({ bot, cl, idapp, msg, data, user, userDest, username_action });
    } else if (act.includes(shared_consts.CallFunz.RICHIESTA_GRUPPO)) {
      notifyText = await handleGroup({ bot, cl, idapp, msg, data, user, userDest, username_action });
    }
    // default
    else {
      notifyText = 'Operazione completata';
      await cl.sendMsg(msg.chat.id, `⚙️ Azione non riconosciuta: ${act}`);
    }

    await bot.answerCallbackQuery(callbackQuery.id, { text: notifyText || 'OK' });
  } catch (err) {
    console.error('❌ callbackHandler error:', err.message);
    try {
      await bot.answerCallbackQuery(callbackQuery.id, { text: 'Errore', show_alert: true });
    } catch (_) {}
  }
}

module.exports = { handleCallback };
