import { subHours, subMinutes, subSeconds } from "date-fns";
import { Op } from "sequelize";
import BotIsOnQueue from "../../helpers/BotIsOnQueue";
import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError";
import { userInfo } from "os"; 
import ShowQueueService from "../QueueService/ShowQueueService";
import UpdateTicketService from "./UpdateTicketService";


const FindOrCreateTicketServiceBot = async (
    contact: Contact,
    whatsappId: number,
    unreadMessages: number,
    groupContact?: Contact
): Promise<any> => {

    try {

        let ticket = await Ticket.findOne({
            where: {
                status: {
                    [Op.or]: ["open", "pending", "queueChoice"]
                },
                contactId: groupContact ? groupContact.id : contact.id
            }
        });

        const { queues, greetingMessage, phoneNumberId } =
          await ShowWhatsAppService(whatsappId);


        //Habilitar esse caso queira usar o bot
        const botInfo = await BotIsOnQueue('botqueue')
        // const botInfo = { isOnQueue: false }



        if (ticket) {
            await ticket.update({ unreadMessages });
        }

        // if (!ticket && groupContact) {
        //     ticket = await Ticket.findOne({
        //         where: {
        //             contactId: groupContact.id
        //         },
        //         order: [["updatedAt", "DESC"]]
        //     });



        //     if (ticket) {

        //         await ticket.update({
        //             status: "pending",
        //             userId: null,
        //             unreadMessages
        //         });
        //     }
        // }

        if (!ticket && !groupContact) {

            console.log('BOT CREATING OR REOPENING THE TICKET')

            ticket = await Ticket.findOne({
                where: {
                    contactId: contact.id,
                    userId: botInfo.userIdBot
                },
                order: [["updatedAt", "DESC"]]
            });

            if (ticket) {

                await ticket.update({
                    status: "open",
                    userId: botInfo.userIdBot,
                    unreadMessages
                });

                console.log('lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

                await dialogFlowStartContext(contact, ticket, botInfo);

            }
        }

        let created = false

        if (!ticket) {

            created = true

            let status = "open"

            if (queues.length > 1 && !botInfo.isOnQueue) {
                status = "queueChoice"
            }

            ticket = await Ticket.create({
              contactId: groupContact ? groupContact.id : contact.id,
              status: status,
              userId: botInfo.userIdBot,
              isGroup: !!groupContact,
              unreadMessages,
              whatsappId,
              phoneNumberId
            });

            console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy')

            await dialogFlowStartContext(contact, ticket, botInfo);

        }

        ticket = await ShowTicketService(ticket.id);

        return { ticket, created };

    } catch (error: any) {
        console.error('===> Error on FindOrCreateTicketServiceBot.ts file: \n', error)
        throw new AppError(error.message);
    }
};

export default FindOrCreateTicketServiceBot;

async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo: any) {

    let msg: any = { type: 'chat', from: `${contact.number}@c.us`, body: '0' };

    let queue = await ShowQueueService(botInfo.botQueueId);

    await UpdateTicketService({
        ticketData: { queueId: queue.id },
        ticketId: ticket.id
    });

    ticket = await ShowTicketService(ticket.id); 

    // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
 
}

