import Ticket from "../../models/Ticket";
import AppError from "../../errors/AppError";
import { Op, where } from "sequelize";
import { Sequelize } from "sequelize";

import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';

import { splitDateTime } from "../../helpers/SplitDateTime";
import Contact from "../../models/Contact";
import Queue from "../../models/Queue";
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))


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

const ListTicketsServiceCache = async ({ 
    status,
    date, 
    userId,  
    queueId
}:Request): Promise<any> => {

    let where_clause = {}

    console.log(' QUEUE ID: ', queueId)

    if (date) {
        where_clause = {
            createdAt: {
                [Op.gte]: date + ' 00:00:00.000000',
                [Op.lte]: date + ' 23:59:59.999999'
            }
        }
    }
    else if(queueId){

      
        where_clause = {
            queueId:  queueId
        }
    }
    else if(userId){ 
      
        where_clause = {
            userId:  userId
        }
    }
    else {
        // where_clause = {
        //     createdAt: {
        //         [Op.gte]: dateToday.fullDate + ' 00:00:00.000000',
        //         [Op.lte]: dateToday.fullDate + ' 23:59:59.999999'
        //       }
        // }
    }


    //where_clause = { ...where_clause, status: status }

    const ticket = await Ticket.findAll({
        where: where_clause, 
        raw: true, 
        // nest:true,
        include:
            [
                {
                    model: Contact,
                    as: "contact",
                    attributes: ["id", "name", "number", "profilePicUrl"]
                },
                {
                    model: Queue,
                    as: "queue",
                    attributes: ["id", "name", "color"]
                }
            ], 
        
        order: [["updatedAt", "DESC"]]
    });


    if (!ticket) {
        throw new AppError("ERR_NO_TICKET_FOUND", 404);
    }

    return ticket;
};

export default ListTicketsServiceCache;