import { Request, Response } from "express";
import AppError from "../errors/AppError";
import { getIO } from "../libs/socket";
import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ShowSchedulingNotifyService from "../services/SchedulingNotifyServices/ShowSchedulingNotifyService";
import { deleteScheduleByTicketIdCache } from "../helpers/SchedulingNotifyCache";
import ShowStatusChatEndService from "../services/StatusChatEndService/ShowStatusChatEndService";

type IndexQuery = {
  contactNumber: string;
  startDate: string;
  endDate: string;
};

export const reportScheduleNotifyByDateStartDateEnd = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const { contactNumber, startDate, endDate } = req.query as IndexQuery;

  const data_query = await ListSchedulingNotifyContactService(
    contactNumber,
    startDate,
    endDate
  );
 
  return res.status(200).json(data_query);
};

export const createOrUpdateScheduleNotify = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const scheduleData = req.body;
  
  const statusChatEnd = await ShowStatusChatEndService({
    name: scheduleData.statusChatEndName
  });

  const schedulingNotifyCreate = await CreateSchedulingNotifyService({
    schedulingNotifyId: scheduleData.schedulingNotifyId,
    ticketId: scheduleData.ticketId,
    statusChatEndId: statusChatEnd.id,
    schedulingDate: scheduleData.schedulingDate,
    schedulingTime: scheduleData.schedulingTime,
    message: scheduleData.message
  });

  // console.group(':::::::::::::::::: DATA schedulingNotifyCreate:\n',schedulingNotifyCreate)
  //  const io = getIO();
  //  io.emit("schedulingNotify", {action: "update", schedulingNotifyCreate });

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

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

  let schedule: any = await ShowSchedulingNotifyService(scheduleId);

  await deleteScheduleByTicketIdCache(schedule.ticketId);

  await DeleteSchedulingNotifyService(scheduleId);

  return res.status(200).send();
};
