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

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

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

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

/**
 * Retrieves all employeeGroups with their parent employeeGroup title.
 * @param {Object} params - The query parameters.
 * @param {number[]} params.employeeGroupsId - The ids of the employeeGroups to retrieve.
 * @returns {Promise<Object>} - The response object with the employeeGroups and success status.
 */
async function getAll(params) {
	try {
		// filter
		const filterConditions = {};

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

		let employeeGroups = [];
		employeeGroups = await dbSAPPS.EmployeeGroup.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.EmployeeGroupTable,
					as: "employeegrouptable",
					include: [
						{
							model: dbSAPPS.User,
							as: "user",
							attributes: ["id", "full_name"],
						},
						{
							model: dbSAPPS.Employee,
							as: "employee",
							attributes: ["id", "employee_name"],
						},
					],
				},
			],
		});

		employeeGroups = employeeGroups.map((employeeGroup) => {
			return {
				...employeeGroup.dataValues,
				company_name: employeeGroup?.company?.display_name,
				employees: employeeGroup?.employeegrouptable.map((eg) => ({
					...eg.dataValues,
					user_full_name: eg?.user?.full_name,
					employee_name: eg?.employee?.employee_name,
				})),
			};
		});

		employeeGroups = await formatWithModifier(employeeGroups);

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

/**
 * Get employeeGroup items with their respective settings.
 * @param {Object} params - An object that contains parameters to filter the employeeGroup items.
 * @param {boolean|string} params.is_parent - A boolean or string indicating whether the employeeGroup items should be parents or not.
 * @returns {Promise<Object>} Resolves with an object that contains the employeeGroup items and a success flag.
 * @example
 * const result = await option({ is_parent: true });
 * console.log(result);
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

		let options = [];
		options = await dbSAPPS.EmployeeGroup.findAll({
			attributes: ["id", "name", "display_name"],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.EmployeeGroupTable,
					as: "employeegrouptable",
					include: [
						{
							model: dbSAPPS.User,
							as: "user",
							attributes: ["id", "full_name"],
						},
						{
							model: dbSAPPS.Employee,
							as: "employee",
							attributes: ["id", "employee_name"],
						},
					],
				},
			],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
				employees: option?.employeegrouptable.map((eg) => ({
					...eg.dataValues,
					user_full_name: eg?.user?.full_name,
					employee_name: eg?.employee?.employee_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 employeeGroup items
 *
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */

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

		const count = await dbSAPPS.EmployeeGroup.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 employeeGroup item.
 *
 * @param {Object} params - The new employeeGroup item data.
 * @param {string} params.name - The name of the employeeGroup item.
 * @param {string} params.title - The title of the employeeGroup item.
 * @param {number} [params.parent_id] - The ID of the parent employeeGroup item.
 * @param {string} [params.url] - The URL of the employeeGroup item.
 * @param {string} [params.icon] - The icon of the employeeGroup item.
 * @param {string} [params.type=link] - The type of the employeeGroup item (link, group, collapse, separator).
 * @param {boolean} [params.enabled=true] - Whether the employeeGroup item is enabled.
 * @param {number} [params.creation=Date.now()] - The creation timestamp of the employeeGroup item.
 * @param {number} [params.modified=Date.now()] - The last modification timestamp of the employeeGroup item.
 * @param {number} [params.owner=1] - The ID of the user who created the employeeGroup item.
 * @param {number} [params.modified_by=1] - The ID of the user who last modified the employeeGroup item.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the employeeGroup item creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingDisplayName = await dbSAPPS.EmployeeGroup.findOne({
			where: { display_name: params.display_name },
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		const employeeGroup = await dbSAPPS.EmployeeGroup.create(params, {
			transaction,
		});

		if (Array.isArray(params.employees) && params.employees.length > 0) {
			// create employees
			const employeesData = params.employees.map((employee) => ({
				...employee,
				employeegroup_id: employeeGroup?.id,
				company_id: params.company_id,
			}));

			// save
			await dbSAPPS.EmployeeGroupTable.bulkCreate(employeesData, {
				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 employeeGroup item.
 *
 * @param {number} id - The ID of the employeeGroup item to update.
 * @param {Object} params - The updated employeeGroup item data.
 * @param {string} [params.name] - The new name of the employeeGroup item.
 * @param {string} [params.title] - The new title of the employeeGroup item.
 * @param {number} [params.parent_id] - The new parent ID of the employeeGroup item.
 * @param {string} [params.url] - The new URL of the employeeGroup item.
 * @param {string} [params.icon] - The new icon of the employeeGroup item.
 * @param {string} [params.type] - The new type of the employeeGroup item (link, group, collapse, separator).
 * @param {boolean} [params.enabled] - Whether the employeeGroup item is enabled or not.
 * @param {number} [params.creation] - The new creation timestamp of the employeeGroup item.
 * @param {number} [params.modified] - The new last modification timestamp of the employeeGroup item.
 * @param {number} [params.owner] - The new ID of the user who created the employeeGroup item.
 * @param {number} [params.modified_by] - The new ID of the user who last modified the employeeGroup item.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the employeeGroup item update process.
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const employeeGroup = await dbSAPPS.EmployeeGroup.findByPk(id);
		if (!employeeGroup) return { success: false, message: "ID not found!" };

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

		// save
		await employeeGroup.update(params, { transaction });

		if (Array.isArray(params.employees) && params.employees.length > 0) {
			await dbSAPPS.EmployeeGroupTable.destroy({
				where: { employeegroup_id: id },
				transaction,
			});

			// create employees
			const employeesData = params.employees.map((employee) => ({
				...employee,
				employeegroup_id: JSON.parse(id),
				company_id: employee.company_id || params.company_id,
			}));

			// save
			await dbSAPPS.EmployeeGroupTable.bulkCreate(employeesData, {
				transaction,
			});
		} else {
			// delete employees
			await dbSAPPS.EmployeeGroupTable.destroy({
				where: { employeegroup_id: id },
				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 employeeGroup
 * @param {number} id - the id of the employeeGroup
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const employeeGroup = await dbSAPPS.EmployeeGroup.findByPk(id);
		if (!employeeGroup) return { success: false, message: "ID not found!" };

		// delete employeegrouptable
		await dbSAPPS.EmployeeGroupTable.destroy({
			where: { employeegroup_id: id },
			transaction,
		});

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