import { get, set } from "./RedisClient";

async function controllByNumber() {
  let tickets = await get({ key: "remote:ticketId*", parse: false }); 

  if (!tickets) return { ticketIds: [], tickets: null };

  let controll: any[] = [];

  for (const ticket of tickets) {
    let match = ticket.match(/"whatsappId":(\d+)/);
    let whatsappId = match ? match[1] : null; 

    const whatsapp = await get({
      key: `whatsapp:${whatsappId}`
    });

    match = whatsapp.match(/"number":"(\d+)"/);
    let number = match ? match[1] : null; 

    match = ticket.match(/"id":(\d+)/);
    let ticketId = match ? match[1] : null; 

    number = JSON.parse(number);
    ticketId = JSON.parse(ticketId); 

    const index = controll.findIndex((c: any) => c.number == number);

    if (index == -1) {
      controll.push({ ticketId, number });
    }
  }

  const ticketIds = controll.map((c: any) => c.ticketId); 

  set(`remote:controll`, JSON.stringify(ticketIds));

  return { ticketIds, tickets };
}

export default controllByNumber;
