import { Request, Response } from "express";
import { getIO } from "../libs/socket";

import CreateTicketService from "../services/TicketServices/CreateTicketService";
import DeleteTicketService from "../services/TicketServices/DeleteTicketService";
import ListTicketsService from "../services/TicketServices/ListTicketsService"; 
import ShowTicketService from "../services/TicketServices/ShowTicketService";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";

import CreateSchedulingNotifyService from  "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ListSchedulingNotifyContactService from  "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
 
import {isScheduling} from "../helpers/CheckSchedulingReminderNotify"
 
 

type IndexQuery = {
  searchParam: string;
  pageNumber: string;
  status: string;
  date: string;
  showAll: string;
  withUnreadMessages: string;
  queueIds: string;
};

interface TicketData {
  contactId: number;
  status: string;
  queueId: number;
  userId: number;
} 


import ListStatusChatEndService from  "../services/StatusChatEndService/ListStatusChatEndService";

export const index = async (req: Request, res: Response): Promise<Response> => {
  const {
    pageNumber,
    status,
    date,
    searchParam,
    showAll,
    queueIds: queueIdsStringified,
    withUnreadMessages
  } = req.query as IndexQuery;

  const userId = req.user.id; 

  let queueIds: number[] = [];

  if (queueIdsStringified) {
    queueIds = JSON.parse(queueIdsStringified);
  } 

  const { tickets, count, hasMore } = await ListTicketsService({
    searchParam,
    pageNumber,
    status,
    date,
    showAll,
    userId,
    queueIds,
    withUnreadMessages
  });
 
  return res.status(200).json({ tickets, count, hasMore });
};

export const store = async (req: Request, res: Response): Promise<Response> => {
  const { contactId, status, userId }: TicketData = req.body;

  // naty 
  // console.log( 
  //   `contactId: ${contactId} \n| status: ${status} \n| userId: ${userId}`
  // )

  const ticket = await CreateTicketService({ contactId, status, userId });

  const io = getIO();
  io.to(ticket.status).emit("ticket", {
    action: "update",
    ticket
  });

  return res.status(200).json(ticket);
};
 

export const show = async (req: Request, res: Response): Promise<Response> => {
  const { ticketId } = req.params;

  const contact = await ShowTicketService(ticketId);

  const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" });  
    
  //////////////////
  const schedulesContact = await ListSchedulingNotifyContactService(contact.contact.number); 
  /////////////////
 

  return res.status(200).json({contact,  statusChatEnd, schedulesContact});
};







export const update = async ( req: Request, res: Response ): Promise<Response> => {

  const { ticketId } = req.params;

  let ticket2 = {}
  
  if(req.body['status'] === "closed"){

    const {status, userId, schedulingNotifyData} = req.body;   

    const { ticket } = await UpdateTicketService({
      ticketData:{'status': status, 'userId': userId},
      ticketId
    });


    ///////////////////////////////
    const whatsapp = await ShowWhatsAppService(ticket.whatsappId);

    const { farewellMessage } = whatsapp;

    if (farewellMessage) {
       await SendWhatsAppMessage({ body: farewellMessage, ticket });
    } 
    ///////////////////////////////

    

    // lembrete
    const scheduleData = JSON.parse(schedulingNotifyData)   
        //  lembrete                              // agendamento
    if( scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3'){
      
      console.log('*** schedulingDate: ', scheduleData.schedulingDate)
      console.log('*** schedulingTime: ', scheduleData.schedulingTime)

      if(isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)){
        console.log('*** É AGENDAMENTO!')
      }
      else{
        console.log('*** É LEMBRETE!')
      }

      const schedulingNotifyCreate = await CreateSchedulingNotifyService(
        {
          ticketId: scheduleData.ticketId,
          statusChatEndId: scheduleData.statusChatEndId, 
          schedulingDate: scheduleData.schedulingDate, 
          schedulingTime: scheduleData.schedulingTime,
          message: scheduleData.message  
        }
      )  
    }
     
    ticket2 = ticket

  }
  else{

    const ticketData: TicketData = req.body;

    const { ticket } = await UpdateTicketService({
      ticketData,
      ticketId
    });

    ticket2 = ticket

  }  

  return res.status(200).json(ticket2);
};






// export const update = async (
//   req: Request,
//   res: Response
// ): Promise<Response> => {
//   const { ticketId } = req.params;
//   const ticketData: TicketData = req.body;

//   const { ticket } = await UpdateTicketService({
//     ticketData,
//     ticketId
//   });

//   if (ticket.status === "closed") {
//     const whatsapp = await ShowWhatsAppService(ticket.whatsappId);

//     const { farewellMessage } = whatsapp;

//     if (farewellMessage) {
//        await SendWhatsAppMessage({ body: farewellMessage, ticket });
//     }
//   }


//   return res.status(200).json(ticket);
// };

export const remove = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const { ticketId } = req.params;
  
  const ticket = await DeleteTicketService(ticketId);

  const io = getIO();
  io.to(ticket.status)
    .to(ticketId)
    .to("notification")
    .emit("ticket", {
      action: "delete",
      ticketId: +ticketId
    });

  return res.status(200).json({ message: "ticket deleted" });
};