const { Op } = require("sequelize");
const dbSAPPS = require("../../helpers/db");
require("dotenv").config();

module.exports = {
  getAll,
  filter,
  option,
  count,
  create,
  update,
  enabled,
  delete: _delete,
};

async function getAll() {
  try {
    // Mengambil semua pengguna dan mengurutkannya berdasarkan kolom 'modified' secara menurun
    const workInstructions = await dbSAPPS.WorkInstruction.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Department,
          as: "department",
          attributes: ["id", "display_name"],
        }
      ]
    });

    // Mengembalikan respons dengan status 200 OK
    return {
      workInstructions,
      success: true,
      message: "Work Instrucions loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "Failed to load Work Instrucions!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function filter(params) {
  // Membuat objek filter dengan validasi
  const filterConditions = {};

  if (params.display_name) {
    filterConditions.display_name = {
      [Op.like]: `%${params.display_name}%`,
    };
  }

  if (params.code) {
    filterConditions.code = {
      [Op.like]: `%${params.code}%`,
    };
  }

  if (params.enabled) {
    filterConditions.enabled = {
      [Op.eq]: params.enabled === "1" ? true : false,
    };
  }
  try {
    // Mencari pengguna berdasarkan filter conditions
    const institutions = await dbSAPPS.WorkInstruction.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]], // Opsional: Mengurutkan hasil berdasarkan kolom 'modified'
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      institutions,
      message: "institutions loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving institutions: ", error);
    const errorMessage =
      error.message || "Failed to retrieve institutions. Please try again later.";
    // Mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function option() {
  try {
    // Mencari pengguna yang diaktifkan dengan atribut tertentu
    const institutions = await dbSAPPS.WorkInstruction.findAll({
      attributes: ["id", "display_name", "code"],
      where: { enabled: true },
      order: [["display_name", "ASC"]], // Opsional: Mengurutkan hasil berdasarkan
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      institutions,
      message: "institutions loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving institutions: ", error);
    const errorMessage =
      error.message || "Failed to retrieve institutions. Please try again later.";
    // Mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function count() {
  try {
    // Menghitung jumlah pengguna yang diaktifkan
    const count = await dbSAPPS.WorkInstruction.count({
      where: { enabled: true },
    });

    // Mengembalikan hasil hitung
    return {
      success: true,
      count,
      message: "institutions loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    console.error("Error counting institutions: ", error);
    return {
      success: false,
      message: "Failed to retrieve institutions count. Please try again later.",
    };
  }
}

async function create(params) {
  try {
    // Periksa apakah email sudah digunakan
    const existingNameNNumber = await dbSAPPS.WorkInstruction.findOne({
      where: {
        title: params.title,
        department_id: params.department_id,
      },
    });
    if (existingNameNNumber)
      return {
        success: false,
        message: `Instruksi Kerja dengan judul ${params.title} sudah ada.`,
      };

    if (!params.enabled) params.enabled = true;
    const newWorkInstruction = await dbSAPPS.WorkInstruction.create(params);

    // Respons sukses
    return {
      success: true,
      message: "Work instruction data has been successfully added!",
      workInstruction: newWorkInstruction,
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage =
      error.message || "An error occurred during create Work instruction processing.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}


async function update(id, params) {
  try {
    const workInstruction = await dbSAPPS.WorkInstruction.findByPk(id);
    if (!workInstruction)
      return {
        success: false,
        message: "Work Instruction not found!",
      };

    await workInstruction.update(params);

    // Respons sukses
    return {
      success: true,
      message: "Work instruction data has been successfully updated!",
      workInstruction,
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage =
      error.message || "An error occurred during update Work instruction processing.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function enabled(id, params) {
  try {
    const workInstruction = await dbSAPPS.WorkInstruction.findByPk(id);
    if (!workInstruction)
      return {
        success: false,
        message: "Work Instruction not found!",
      };

    const updateData = {};
    updateData.enabled = params.enabled;
    if (params.modified_by) updateData.modified_by = params.modified_by;
    if (params.modified) updateData.modified = params.modified;

    // debug
    // console.log('id', id);
    // console.log('params', params);
    // console.log('updateData', updateData)

    await workInstruction.update(updateData);

    return {
      success: true,
      message: "Work Instruction has been updated!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update Work Instruction.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function _delete(id) {
  try {
    // Mengambil pengguna dari database
    const workInstruction = await dbSAPPS.WorkInstruction.findByPk(id);
    if (!workInstruction) return { success: false, message: "Work instruction not found!" };

    // Menghapus pengguna dari database
    await workInstruction.destroy();

    // Respons sukses
    return {
      success: true,
      message: "Work instruction successfully deleted!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to delete Work instruction.";
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}
