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

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

/**
 * Format an array of leavePeriods 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[]} leavePeriods - The array of leavePeriods to format.
 * @returns {Promise<Object[]>} - The formatted array of leavePeriods.
 */
const formatWithModifier = async (leavePeriods) => {
	return Promise.all(
		leavePeriods.map(async (leavePeriod) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: leavePeriod.modified_by,
				},
				attributes: ["full_name"],
			});

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

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

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

		if (params.from_date && params.to_date) {
			filterConditions.from_date = {
				[Op.lte]: params.from_date,
			};
			filterConditions.to_date = {
				[Op.gte]: params.to_date,
			};
		}

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

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

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

		leavePeriods = await formatWithModifier(leavePeriods);

		return {
			leavePeriods,
			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,
			};
		}

		if (params.from_date && params.to_date) {
			filterConditions.from_date = {
				[Op.lte]: params.from_date,
			};
			filterConditions.to_date = {
				[Op.gte]: params.to_date,
			};
		}

		// must be is_active
		filterConditions.is_active = {
			[Op.eq]: true,
		};

		let options = [];
		options = await dbSAPPS.LeavePeriod.findAll({
			attributes: ["id", "name", "display_name"],
			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 = {};

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

		if (params.from_date && params.to_date) {
			filterConditions.from_date = {
				[Op.lte]: params.from_date,
			};
			filterConditions.to_date = {
				[Op.gte]: params.to_date,
			};
		}

		// must be is_active
		filterConditions.is_active = {
			[Op.eq]: true,
		};

		const count = await dbSAPPS.LeavePeriod.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.LeavePeriod.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;
		if (!params.is_active) params.is_active = true;

		// save
		await dbSAPPS.LeavePeriod.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 leavePeriod = await dbSAPPS.LeavePeriod.findByPk(id);
		if (!leavePeriod) return { success: false, message: "ID not found!" };

		// validate existing
		const existing = await dbSAPPS.LeavePeriod.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 leavePeriod.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 enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const leavePeriod = await dbSAPPS.LeavePeriod.findByPk(id);
		if (!leavePeriod) return { success: false, message: "ID not found!" };

		// update params
		const updateData = {};
		updateData.enabled = params.enabled;
		updateData.is_active = params.is_active;
		if (params.modified_by) updateData.modified_by = params.modified_by;
		if (params.modified) updateData.modified = params.modified;

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

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

		// validate used in leaveAllocation
		const usedInLeaveAllocation = await dbSAPPS.LeaveAllocation.count({
			where: {
				leaveperiod_id: id,
			},
			transaction,
		});
		if (usedInLeaveAllocation > 0) {
			throw new Error(
				`This leave period is being used in Leave Allocation, cannot be deleted!`
			);
		}		

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