const {
  getAllNotificationErrorSparepartDb,
  getNotificationErrorSparepartByIdDb,
  createNotificationErrorSparepartDb,
  updateNotificationErrorSparepartDb,
  deleteNotificationErrorSparepartDb,
} = require("../db/notification_error_sparepart.db");

const { getContactByIdDb } = require("../db/contact.db");
const { ErrorHandler } = require("../helpers/error");

class NotificationErrorSparepartService {
  static _checkAccess(contactType) {
    if (contactType !== "gudang") {
      throw new ErrorHandler(
        403,
        "Akses ditolak. Hanya contact_type 'gudang' yang dapat getAll/create/update/delete."
      );
    }
  }

  static async getAll(param, contact_id) {
     const contactResult = await getContactByIdDb(contact_id);

    if (!contactResult || contactResult.length < 1)
      throw new ErrorHandler(404, "Contact tidak ditemukan");

    const contact = contactResult[0];

    this._checkAccess(contact.contact_type);
    return await getAllNotificationErrorSparepartDb(param);
  }

  static async getById(id) {
    const result = await getNotificationErrorSparepartByIdDb(id);

    if (result.length < 1)
      throw new ErrorHandler(404, "Notification Error Sparepart not found");

    return result;
  }

  static async create(data) {
    const contactResult = await getContactByIdDb(data.contact_id);

    if (!contactResult || contactResult.length < 1)
      throw new ErrorHandler(404, "Contact tidak ditemukan");

    const contact = contactResult[0];

    this._checkAccess(contact.contact_type);

    return await createNotificationErrorSparepartDb(data);
  }

  static async update(id, data) {
    const contactResult = await getContactByIdDb(data.contact_id);

    if (!contactResult || contactResult.length < 1)
      throw new ErrorHandler(404, "Contact tidak ditemukan");

    const contact = contactResult[0];

    this._checkAccess(contact.contact_type);

    const exist = await getNotificationErrorSparepartByIdDb(id);

    if (exist.length < 1)
      throw new ErrorHandler(404, "Notification Error Sparepart not found");

    return await updateNotificationErrorSparepartDb(id, data);
  }

  static async delete(id, contact_id) {
    const contactResult = await getContactByIdDb(contact_id);

    if (!contactResult || contactResult.length < 1)
      throw new ErrorHandler(404, "Contact tidak ditemukan");

    const contact = contactResult[0];

    this._checkAccess(contact.contact_type);

    const exist = await getNotificationErrorSparepartByIdDb(id);

    if (exist.length < 1)
      throw new ErrorHandler(404, "Notification Error Sparepart not found");

    return await deleteNotificationErrorSparepartDb(id);
  }
}

module.exports = NotificationErrorSparepartService;
