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 = {};
	const safeParams = params && typeof params === "object" ? params : {};
	const andConditions = [];

	// Backward compatible: old param name
	if (safeParams.name && String(safeParams.name).trim().length > 0) {
		andConditions.push({
			name: {
				[Op.like]: `%${String(safeParams.name).trim()}%`,
			},
		});
	}

	// Column filters (pattern: f_*)
	if (safeParams.f_name && String(safeParams.f_name).trim().length > 0) {
		andConditions.push({
			name: {
				[Op.like]: `%${String(safeParams.f_name).trim()}%`,
			},
		});
	}
	if (safeParams.f_display_name && String(safeParams.f_display_name).trim().length > 0) {
		andConditions.push({
			display_name: {
				[Op.like]: `%${String(safeParams.f_display_name).trim()}%`,
			},
		});
	}

	// Global search (pattern: q)
	if (safeParams.q && String(safeParams.q).trim().length > 0) {
		const q = String(safeParams.q).trim();
		andConditions.push({
			[Op.or]: [{ name: { [Op.like]: `%${q}%` } }, { display_name: { [Op.like]: `%${q}%` } }],
		});
	}

	if (safeParams.enabled !== undefined && safeParams.enabled !== null && String(safeParams.enabled).length > 0) {
		andConditions.push({
			enabled: {
				[Op.eq]: String(safeParams.enabled) === "1" || String(safeParams.enabled).toLowerCase() === "true",
			},
		});
	}

	if (andConditions.length > 0) {
		filterConditions[Op.and] = andConditions;
	}
	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,
		};
	}
}
