import QuickAnswer from "../../models/QuickAnswer";
import AppError from "../../errors/AppError";
import AssociateQuickAnswerQueue from "../QueueService/AssociateQuickAnswerQueue";
import StatusChatEnd from "../../models/StatusChatEnd";
import { set } from "../../helpers/RedisClient";
import { update } from "../../controllers/UserController";
import { Op, where } from "sequelize";

interface StatusChatEndData {
  name?: string;
  farewellMessage?: string;
  isDefault?: boolean;
}

interface Request {
  statusChatEndData: StatusChatEndData;
  statusChatEndId: string;
}

const UpdateStatusChatEndService = async ({
  statusChatEndData,
  statusChatEndId
}: Request): Promise<StatusChatEnd> => {
  const { name, farewellMessage, isDefault } = statusChatEndData;

  if (isDefault) {
    StatusChatEnd.update(
      { isDefault: false },
      { where: { id: { [Op.gte]: 0 } } }
    );
  }

  const statusChatEnd = await StatusChatEnd.findOne({
    where: { id: statusChatEndId },
    attributes: ["id", "name", "farewellMessage", "isDefault"]
  });

  if (!statusChatEnd) {
    throw new AppError("ERR_NO_STATUS_CHAT_END_FIND", 404);
  }
  await statusChatEnd.update({
    name,
    farewellMessage,
    isDefault
  });

  await statusChatEnd.reload({
    attributes: ["id", "name", "farewellMessage", "isDefault"]
  });

  const { id } = statusChatEnd;
  await set(`statusChatEnd:${id}`, { id, name, farewellMessage, isDefault });

  return statusChatEnd;
};

export default UpdateStatusChatEndService;
