import { Sequelize } from "sequelize";

const dbConfig = require("../../config/database");
const sequelize = new Sequelize(dbConfig);
const { QueryTypes } = require("sequelize");

import { splitDateTime } from "../../helpers/SplitDateTime";
import format from "date-fns/format";
import ptBR from "date-fns/locale/pt-BR";

interface Request {
  timeseconds: string | number;
  status: string;
  number?: string;
  userId?: string | number;
}

const ListTicketTimeLife = async ({
  timeseconds,
  status,
  number,
  userId
}: Request): Promise<any[]> => {
  let tickets = [];

  let currentDate = format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR });

  // console.log('------------------> currentDate: ', currentDate)

  if (userId) {
    // CONSULTANDO FILAS PELO ID DO USUARIO
    tickets = await sequelize.query(
      `select user.id as user_id, user.name as user_name, t.id as ticket_id from Tickets as t inner join Users as user on
        t.userId = user.id and user.name = 'botqueue' and t.status='${status}' and (TIMESTAMPDIFF(SECOND, t.updatedAt, '${currentDate}')) >= ${timeseconds};`,
      { type: QueryTypes.SELECT }
    );
  } else if (number) {
    // CONSULTANDO TICKETS PELO WHATSAPP
    tickets = await sequelize.query(
      `SELECT t.id AS ticket_id
       FROM Tickets t
       JOIN Whatsapps w ON t.whatsappId = w.id 
       AND w.number = ${number}
       WHERE t.status = 'open' 
       AND TIMESTAMPDIFF(SECOND, t.updatedAt, '${currentDate}') >= ${timeseconds};`,
      { type: QueryTypes.SELECT }
    ); 
  } else {
    // CONSULTANDO FILAS PELO USUARIO
    tickets = await sequelize.query(
      `select id as ticket_id from Tickets where status='${status}' and 
        (TIMESTAMPDIFF(SECOND, updatedAt, '${currentDate}')) >= ${timeseconds};`,
      { type: QueryTypes.SELECT }
    );
  }

  return tickets;
};

export default ListTicketTimeLife;
