import ListTicketTimeLife from "../services/TicketServices/ListTicketTimeLife";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import BotIsOnQueue from "./BotIsOnQueue";

const fsPromises = require("fs/promises");
const fs = require('fs')

let timer: any

const CloseBotTickets = async () => {

  try {

    const botInfo = await BotIsOnQueue('botqueue')

    if (!botInfo.userIdBot) return

    let tickets: any = await ListTicketTimeLife({ timeseconds: 60, status: 'open', userId: botInfo.userIdBot })

    console.log('tickets: ', tickets)

    for (let i = 0; i < tickets.length; i++) {

      await UpdateTicketService({
        ticketData: { 'status': 'closed', 'userId': botInfo.userIdBot, 'statusChatEnd': 'FINALIZADO' },
        ticketId: tickets[i].ticket_id
      });

    }

  } catch (error) {
    console.log('There was an error on try close the bot tickets: ', error)
  }

}

const schedule = async () => {

  try {
    clearInterval(timer);

    await CloseBotTickets()

  } catch (error) {
    console.log('error on schedule: ', error)
  }
  finally {
    timer = setInterval(schedule, 60000);
  }
}

timer = setInterval(schedule, 60000);

export default schedule;