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 institutions = await dbSAPPS.Institution.findAll({
      order: [["modified", "DESC"]],
    });

    // Mengembalikan respons dengan status 200 OK
    return {
      institutions,
      success: true,
      message: "institutions loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "Failed to load institutions!";
    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.Institution.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.Institution.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.Institution.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 {
    // Validasi input
    if (!params.display_name || !params.code)
      return {
        success: false,
        message: "institutions name and institutions code are required!",
      };

    // Periksa apakah email sudah digunakan
    const existingNameNNumber = await dbSAPPS.Institution.findOne({
      where: {
        display_name: params.display_name,
        code: params.code,
      },
    });
    if (existingNameNNumber)
      return {
        success: false,
        message: `institutions name "${params.display_name}" and code "${params.code}" is already taken.`,
      };

    if (!params.enabled) params.enabled = true;
    const newinstitutions = await dbSAPPS.Institution.create(params);

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

async function update(id, params) {
  try {
    // Ambil dari database
    const institutions = await dbSAPPS.Institution.findByPk(id);
    if (!institutions)
      return {
        success: false,
        message: "institutions not found!",
      };

    // Validasi perubahan
    if (params.display_name && params.display_name !== institutions.display_name) {
      const existinginstitutionsName = await dbSAPPS.Institution.findOne({
        where: { display_name: params.display_name },
      });
      if (existinginstitutionsName) {
        return {
          success: false,
          message: `institutions name "${params.display_name}" is already taken. Try again!`,
        };
      }
    }

    if (params.code && params.code !== institutions.code) {
      const existinginstitutionsCode = await dbSAPPS.Institution.findOne({
        where: { code: params.code },
      });
      if (existinginstitutionsCode) {
        return {
          success: false,
          message: `institutions code "${params.code}" is already taken. Try again!`,
        };
      }
    }

    // Perbarui data provinsi
    await institutions.update(params);

    // Respons sukses
    return {
      success: true,
      message: "Data institutions has been saved!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update institutions data.";
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function enabled(id, params) {
  try {
    const institutions = await dbSAPPS.Institution.findByPk(id);
    if (!institutions)
      return {
        success: false,
        message: "institutions 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 institutions.update(updateData);

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

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

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

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