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

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

/**
 * Format an array of educationLevels by appending a modifier field.
 * @param {Object[]} educationLevels - The array of educationLevels to format.
 * @returns {Promise<Object[]>} - The formatted array of educationLevels.
 */
const formatWithModifier = async (educationLevels) => {
	return Promise.all(
		educationLevels.map(async (educationLevel) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: educationLevel.modified_by,
				},
				attributes: ["full_name"],
			});

			return {
				...educationLevel,
				modifier: modifier?.full_name,
			};
		})
	);
};

/**
 * Get all educationLevels with their respective companies.
 * @param {Object} params - An object that contains parameters to filter the educationLevels.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the educationLevels and a success flag.
 */
async function getAll(params) {
	try {
		const filterConditions = {};

		if (params.companiesId && params.companiesId.length) {
			// ROBUST: Include NULL company_id (global/shared data) when filtering by companies
			filterConditions[Op.or] = [
				{ company_id: { [Op.in]: params.companiesId } },
				{ company_id: null }
			];
		}

		let educationLevels = [];
		educationLevels = await dbSAPPS.EducationLevel.findAll({
			where: filterConditions,
			order: [["level_order", "ASC"], ["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
			],
		});

		educationLevels = educationLevels.map((educationLevel) => {
			return {
				...educationLevel.dataValues,
				company_name: educationLevel?.company?.display_name,
			};
		});

		educationLevels = await formatWithModifier(educationLevels);

		return {
			educationLevels,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Get educationLevels with their respective settings (for dropdown/options).
 * @param {Object} params - An object that contains parameters to filter the educationLevels.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the educationLevels and a success flag.
 */
async function option(params) {
	try {
		const filterConditions = {};

		if (params.company_id) {
			filterConditions.company_id = {
				[Op.eq]: params.company_id,
			};
		}

		if (params.companiesId && params.companiesId.length) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}

		filterConditions.enabled = {
			[Op.eq]: true,
		};

		let options = [];
		options = await dbSAPPS.EducationLevel.findAll({
			where: filterConditions,
			attributes: ["id", "name", "display_name", "level_order"],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
			],
			order: [["level_order", "ASC"], ["name", "ASC"]],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
			};
		});

		return {
			options,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Count active educationLevels
 * @returns {Promise<{count: number, success: boolean, message: string}>}
 */
async function count(params) {
	try {
		const filterConditions = {};
		filterConditions.enabled = {
			[Op.eq]: true,
		};

		const count = await dbSAPPS.EducationLevel.count({
			where: filterConditions,
		});

		return {
			count,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Creates a new educationLevel
 * @param {object} params - educationLevel data to be created.
 * @returns {Promise<{success: boolean, message: string}>} Result of the educationLevel creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const existingName = await dbSAPPS.EducationLevel.findOne({
			where: { name: params.name, company_id: params.company_id || null },
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.EducationLevel.findOne({
			where: {
				display_name: params.display_name,
				company_id: params.company_id || null,
			},
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		await dbSAPPS.EducationLevel.create(params, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Updates an existing educationLevel
 * @param {number} id - educationLevel ID to be updated.
 * @param {object} params - educationLevel data to be updated.
 * @returns {Promise<{success: boolean, message: string}>} Result of the educationLevel update process.
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const educationLevel = await dbSAPPS.EducationLevel.findByPk(id);
		if (!educationLevel) return { success: false, message: "ID not found!" };

		const existingName = await dbSAPPS.EducationLevel.findOne({
			where: {
				name: params.name,
				company_id: params.company_id ?? educationLevel.company_id,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.EducationLevel.findOne({
			where: {
				display_name: params.display_name,
				company_id: params.company_id ?? educationLevel.company_id,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		await educationLevel.update(params, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Enable or disable a educationLevel
 * @param {number} id - the id of the educationLevel
 * @param {object} params - the update data
 * @returns {Promise<object>} - the result of the update
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const educationLevel = await dbSAPPS.EducationLevel.findByPk(id);
		if (!educationLevel) return { success: false, message: "ID 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;

		await educationLevel.update(updateData, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Delete a educationLevel
 * @param {number} id - the id of the educationLevel
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const educationLevel = await dbSAPPS.EducationLevel.findByPk(id, { transaction });
		if (!educationLevel) return { success: false, message: "ID not found!" };

		// Check if used by employees
		const employeeCount = await dbSAPPS.Employee.count({
			where: { education_level_id: id },
			transaction,
		});
		if (employeeCount > 0) {
			return {
				success: false,
				message: `Cannot delete. This education level is used by ${employeeCount} employee(s).`,
			};
		}

		await educationLevel.destroy({ transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Deleted successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to delete, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}
