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";
import Whatsapp from "../../models/Whatsapp";

//Report by user, startDate, endDate
const ShowMessageReport = async (id: string | number, startDate: string, endDate: string): Promise<any[]> => {   
  
  let where_clause_user = {}

   let where_clause = {      
      createdAt: {
        [Op.gte]: startDate+' 00:00:00.000000',
        [Op.lte]: endDate  +' 23:59:59.999999'
      }, 
    }

  if(id=='0'){ 

    // where_clause_user = {   
    //   createdAt: {
    //     [Op.gte]: startDate+' 00:00:00.000000',
    //     [Op.lte]: endDate  +' 23:59:59.999999'
    //   }, 
    // }
   
  }
  else{
    where_clause_user = {  
      userid: id,    
      // createdAt: {
      //   [Op.gte]: startDate+' 00:00:00.000000',
      //   [Op.lte]: endDate  +' 23:59:59.999999'
      // }, 
    }
  }

  const messages = await Message.findAll({  

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

    include: [
      {
        model: Ticket,
        where: where_clause_user,
        required:true,  
    
        attributes: ['id', 'status', 'statusChatEnd'],
        
        include: [
          {
            model: Contact,  
            attributes: ['name', 'number']            
          },
          {
            model: User, 
            attributes: ['name', 'email']
          },
          {
            model: Queue, 
            attributes: ['name']
          },
          {
            model: Whatsapp, 
            attributes: ['name']
          },
        ]
      
      }, 
    
    ], 

    order: [
      ['createdAt', 'ASC']
    ]  
   
  });  
 
  
  if (!messages) {
    throw new AppError("ERR_NO_MESSAGES_FOUND", 404);
  }

  return messages;
}; 

export default ShowMessageReport;
