import Ticket from "../../models/Ticket";
import AppError from "../../errors/AppError";
import Contact from "../../models/Contact";
import User from "../../models/User";
import Queue from "../../models/Queue";

import Message from "../../models/Message";
import { userInfo } from "os";

import { Op, where } from "sequelize";

import { Sequelize } from "sequelize"; 
import moment from 'moment';  
 
import { startOfDay, endOfDay, parseISO, getDate} from "date-fns"; 
import { string } from "yup/lib/locale";

//Report by user, startDate, endDate
const ShowTicketMessage = async (ticketId: string | number, onlyNumber: boolean = false, limit?: number, regexp?: string): Promise<Message[]> => {   
  
  let where_clause = {}

  if(onlyNumber){
    where_clause = {  
      ticketId: ticketId,   
      fromMe: 0, 
      //body: {[Op.regexp]: '^[0-9]*$'}, 
      // body: {[Op.regexp]: '^[0-3]$'}, 
      body: {[Op.regexp]: regexp},
    } 
  }
  else{
    where_clause = {  
      ticketId: ticketId,   
      fromMe: 0,  
    } 
  }

  
  const ticket = await Message.findAll({  

    where: where_clause ,   
    limit: limit ? limit : 10000,
    raw:true,
    attributes: ['body', 'read', 'mediaType','fromMe', 'mediaUrl', [Sequelize.fn("DATE_FORMAT",Sequelize.col("createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"]],

    order: [
      ['createdAt', 'DESC']
    ]  
   
  });  
 
  
  if (!ticket) {
    throw new AppError("ERR_NO_TICKET_FOUND", 404);
  }

  return ticket;
}; 

export default ShowTicketMessage;
