import { ResultSetHeader, RowDataPacket } from "mysql2";
import DB from "../config/database/db";
import notificationTypes from "../schemas/notification.schema";
import CONSTANTS from "../config/constants";

const notificationDB: any = {};

notificationDB.getByUserId = async ({
  userId,
  userType,
  pageNum,
  limit,
}: notificationTypes & { pageNum: number; limit: number }) => {
  const query =
    "Select * from Notifications where userId=? and userType = ? order by id desc  limit ?, ?";

  const offset: number = (pageNum - 1) * limit;
  const data = [userId, userType, `${offset}`, `${limit}`];

  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows;
  else return false;
};

notificationDB.getUnreadNotifications = async ({
  userId,
  userType,
}: notificationTypes) => {
  const query =
    "Select COUNT(id) as count from Notifications where userId=? and userType = ? and status = ?";

  const data = [userId, userType, CONSTANTS.NOTIFICATION_STATUS.PENDING];

  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0].count;
  else return false;
};

notificationDB.add = async ({
  userId,
  userType,
  title,
  message,
  notiCategory
}: notificationTypes) => {
  const query =
    "Insert into Notifications (userId, userType, title, message, notiCategory) values (?, ?, ?, ?, ?)";
  const data = [userId, userType, title, message, notiCategory];
  await DB.execute<ResultSetHeader[]>(query, data);
  return true;
};

notificationDB.updateStatus = async ({
  userId,
  userType,
  status,
  statusToUpdate,
}: notificationTypes & { statusToUpdate: number }) => {
  const query =
    "Update Notifications set status = ? where userId=? and userType = ? and status = ?";
  const data = [status, userId, userType, statusToUpdate];
  await DB.execute<ResultSetHeader[]>(query, data);
  return true;
};

notificationDB.removeByUserId = async ({ userId }: notificationTypes) => {
  const query = "Delete from Notifications where userId=?";
  const data = [userId];
  await DB.execute<ResultSetHeader[]>(query, data);
  return true;
};

export default notificationDB;
