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

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

/**
 * Format an array of leaveTypes by appending a modifier field to each company.
 * The modifier field is the full name of the user who last modified the company.
 * @param {Object[]} leaveTypes - The array of leaveTypes to format.
 * @returns {Promise<Object[]>} - The formatted array of leaveTypes.
 */
const formatWithModifier = async (leaveTypes) => {
	return Promise.all(
		leaveTypes.map(async (leaveType) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: leaveType.modified_by,
				},
				attributes: ["full_name"],
			});

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

async function getAll(params) {
	try {
		// filter
		const filterConditions = {};

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

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

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

		leaveTypes = await formatWithModifier(leaveTypes);

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

async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

		const conditions = [];

		if (params.is_lwp) {
			conditions.push({
				is_lwp: {
					[Op.eq]: true,
				},
			});
		} else {
			filterConditions.is_lwp = false;
		}

		if (params.is_sl) {
			conditions.push({
				is_sl: {
					[Op.eq]: true,
				},
			});
		} else {
			filterConditions.is_sl = false;
		}

		if (conditions.length > 0) {
			filterConditions[Op.or] = conditions;
		}

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

		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,
		};
	}
}

async function count(params) {
	try {
		// filter
		const filterConditions = {};

		const count = await dbSAPPS.LeaveType.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,
		};
	}
}

async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.LeaveType.findOne({
			where: {
				display_name: params.display_name,
				name: params.name,
				company_id: params.company_id,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		if (!params.enabled) params.enabled = true;

		// save
		await dbSAPPS.LeaveType.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,
		};
	}
}

async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const leaveType = await dbSAPPS.LeaveType.findByPk(id);
		if (!leaveType) return { success: false, message: "ID not found!" };

		// validate existing
		const existing = await dbSAPPS.LeaveType.findOne({
			where: {
				display_name: params.display_name,
				name: params.name,
				company_id: params.company_id,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		await leaveType.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,
		};
	}
}

async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const leaveType = await dbSAPPS.LeaveType.findByPk(id, { transaction });
		if (!leaveType) return { success: false, message: "ID not found!" };

		// delete
		await leaveType.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,
		};
	}
}
