// routes.js
import express from 'express';
import axios   from 'axios';
import dayjs from 'dayjs';
import { config }           from './config.js';
import { log }              from './logger.js';
import { sendText }         from './whatsapp.js';
import { processIncoming }  from './handlers.js';
import { processMessage } from './utils/processMessage.js';

// chats a tomar en cuenta para el bot

const relevantChats = [
  '50496210031@c.us',
  '120363203056794284@g.us',
  '120363398335375917@g.us',
  '50498554225@c.us',
  '50496934012@c.us',
  '50497588328@c.us',
  '50489701450@c.us' 
]




export const router = express.Router();

// --- Manejo de eventos del webhook ------------------------------------------------
router.post('/webhook', async (req, res) => {
  const { event, data: raw } = req.body;
  const data = processMessage(raw);
  
  // Si el evento no es relevante, ignorar
  if(data.chatId && !relevantChats.includes(data.chatId)) {
    log('info', `Mensaje de ${data.chatId} ignorado`);
    return res.sendStatus(200);
  }
  // console.log('----------------------------------------------------------------');
  // log('debug', '↪︎ Mensaje IN →', raw);
  // console.log('----------------------------------------------------------------');
  
  // log('debug', `📩 Webhook event "${event}"`);

  switch (event) {
    case 'onAck':
      log('info', 'Ack:', data);
      break;

    case 'onAddedToGroup':
      log('info', 'Added to group:', data);
      break;

    case 'onAnyMessage':
      // log('info', 'onAnyMessage', data);
      log('info', 'onAnyMessage', raw.chatId);
      await processIncoming(raw);
      break;

    case 'onBattery':
      log('info', 'Battery status:', data);
      break;

    case 'onBroadcast':
      log('info', 'Broadcast:', data);
      break;

    case 'onButton':
      log('info', 'Button pressed:', data);
      break;

    case 'onCallState':
      log('info', 'Call state:', data);
      break;

    case 'onChatDeleted':
      log('info', 'Chat deleted:', data);
      break;

    case 'onChatOpened':
      log('info', 'Chat opened:', data);
      break;

    case 'onChatState':
      log('info', 'Chat state:', data);
      break;

    case 'onContactAdded':
      log('info', 'Contact added:', data);
      break;

    case 'onGlobalParticipantsChanged':
      log('info', 'Global participants changed:', data);
      break;

    case 'onGroupApprovalRequest':
      log('info', 'Group approval request:', data);
      break;

    case 'onGroupChange':
      log('info', 'Group change:', data);
      break;

    case 'onIncomingCall':
      log('info', 'Incoming call:', data);
      break;

    case 'onLabel':
      log('info', 'Label event:', data);
      break;

    case 'onLogout':
      log('info', 'Logout:', data);
      break;

    case 'onMessage':
      log('info', 'Message:', data);
      break;

    case 'onMessageDeleted':
      log('info', 'Message deleted:', data);
      break;

    case 'onNewProduct':
      log('info', 'New product:', data);
      break;

    case 'onOrder':
      log('info', 'Order:', data);
      break;

    case 'onPlugged':
      log('info', 'Plugged:', data);
      break;

    case 'onPollVote':
      log('info', 'Poll vote:', data);
      break;

    case 'onReaction':
      log('info', 'Reaction:', data);
      break;

    case 'onRemovedFromGroup':
      log('info', 'Removed from group:', data);
      break;

    case 'onStateChanged':
      log('info', 'State changed:', data);
      break;

    case 'onStory':
      log('info', 'Story:', data);
      break;

    default:
      log('warn', `Unhandled event type: "${event}"`, data);
      break;
  }

  res.sendStatus(200);
});
















// comentado el 4/26/2025
/* Debug: escanear últimos mensajes */
// router.get('/debug/scan', async (_req, res) => {
//   const { data } = await axios.post(`${config.API_URL}/loadAndGetAllMessagesInChat`, {
//     args: { chatId: config.GROUP_ID, includeMe: 'true', includeNotifications: 'false' }
//   });
//   const msgs = (data?.response ?? []).slice(-20);
//   log('info', `Escaneando ${msgs.length} mensajes recientes…`);
//   for (const m of msgs) await processIncoming(m);
//   res.json({ ok: true, scanned: msgs.length });
// });

/* Debug: enviar mensaje */
// router.get('/debug/send', async (req, res) => {
//   const text = req.query.msg ?? config.REPLY_MSG;
//   const resp = await sendText(config.GROUP_ID, text);
//   res.json({ ok: true, resp });
// });

/* Debug: versión */
router.get('/debug/version', (_req, res) => {
  res.json({ version: config.VERSION });
});
