const pool = require("../config");

const createNotificationErrorLogDb = async (data) => {
  const store = {
    notification_error_id: data.notification_error_id,
    contact_id: data.contact_id,
    notification_error_log_description: data.notification_error_log_description,
    created_by: data.created_by
  };

  const { query: queryText, values } = pool.buildDynamicInsert("notification_error_log", store);
  const result = await pool.query(queryText, values);
  return result.recordset[0];
};

const getAllNotificationErrorLogDb = async () => {
  const queryText = `
    SELECT
      a.*
    FROM notification_error_log a
    WHERE a.deleted_at IS NULL
    ORDER BY a.notification_error_log_id DESC
  `;
  const result = await pool.query(queryText);
  return result.recordset;
};

const getNotificationErrorLogByIdDb = async (id) => {
  const queryText = `
    SELECT
      a.*
    FROM notification_error_log a
    WHERE a.notification_error_log_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset[0];
};

const updateNotificationErrorLogDb = async (id, data) => {
  const store = { ...data };
  const whereData = {
    notification_error_log_id: id
  };

  const { query: queryText, values } = pool.buildDynamicUpdate("notification_error_log", store, whereData);
  await pool.query(`${queryText} AND deleted_at IS NULL`, values);
  return true;
};

const deleteNotificationErrorLogDb = async (id, deletedBy) => {
  const queryText = `
    UPDATE notification_error_log
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE notification_error_log_id = $2 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, id]);
  return true;
};

module.exports = {
  createNotificationErrorLogDb,
  getAllNotificationErrorLogDb,
  getNotificationErrorLogByIdDb,
  updateNotificationErrorLogDb,
  deleteNotificationErrorLogDb,
};