import User from "../../models/User";
import AppError from "../../errors/AppError";
import Ticket from "../../models/Ticket";
import UpdateDeletedUserOpenTicketsStatus from "../../helpers/UpdateDeletedUserOpenTicketsStatus";
import { set } from "../../helpers/RedisClient";

const DeleteUserService = async (
  id: string | number,
  ignoreThrow = false
): Promise<void | any> => {
  const user = await User.findOne({
    where: { id }
  });

  if (!user) {
    if (ignoreThrow)
      return {
        error: true,
        msg: `No user found with this id ${id}`,
        status: 404
      };

    throw new AppError("ERR_NO_USER_FOUND", 404);
  }

  if (user?.name?.trim() == "botqueue") {
    let botInfo = JSON.stringify({
      userId: 0,
      queueId: 0,
      botIsOnQueue: false
    });
    botInfo = JSON.parse(botInfo);

    await set("botInfo", botInfo);
  }

  const userOpenTickets: Ticket[] = await user.$get("tickets", {
    where: { status: "open" }
  });

  if (userOpenTickets.length > 0) {
    UpdateDeletedUserOpenTicketsStatus(userOpenTickets);
  }

  await user.destroy();
};

export default DeleteUserService;
