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 faculties = await dbSAPPS.Faculty.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Major,
          as: "majors",
          attributes: ["id", "name", "faculty_id", "display_name"],
        },
      ],
    });

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

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

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


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

    // Mengembalikan hasil pencarian
    return {
      success: true,
      faculties,
      message: "faculties loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving faculties: ", error);
    const errorMessage =
      error.message || "Failed to retrieve faculties. 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 faculties = await dbSAPPS.Faculty.findAll({
      attributes: ["id", "name","display_name"],
      where: { enabled: true },
      order: [["name", "ASC"]], // Opsional: Mengurutkan hasil berdasarkan
      include: [
        {
          model: dbSAPPS.Major,
          as: "majors",
          attributes: ["id", "name","faculty_id", "display_name"],
          where: { enabled: true }, // Only include enabled majors
          required: false, // Left join instead of inner join
        },
      ],
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      faculties,
      message: "faculties loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving faculties: ", error);
    const errorMessage =
      error.message || "Failed to retrieve faculties. 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.Faculty.count({
      where: { enabled: true },
    });

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

async function create(params) {
  try {
    // Validasi input
    if (!params.name)
      return {
        success: false,
        message: "Faculty name are required!",
      };

    // Periksa apakah nama fakultas sudah digunakan
    const existingFacultyName = await dbSAPPS.Faculty.findOne({
      where: {
        name: params.name,
      },
    });
    if (existingFacultyName)
      return {
        success: false,
        message: `Faculty name "${params.name}" is already taken.`,
      };

    if (!params.enabled) params.enabled = true;
    const newFaculty = await dbSAPPS.Faculty.create(params);

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

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

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


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

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

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

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

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

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

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