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

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

/**
 * Retrieves all
 */
async function getAll(params) {
	try {
		// base filters
		const filterConditions = {};

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

		// column filters
		if (params.f_name) {
			filterConditions.name = {
				[Op.iLike]: `%${params.f_name}%`,
			};
		}

		if (params.f_title) {
			filterConditions.title = {
				[Op.iLike]: `%${params.f_title}%`,
			};
		}

		if (params.f_type) {
			filterConditions.type = {
				[Op.iLike]: `%${params.f_type}%`,
			};
		}

		if (params.f_url) {
			filterConditions.url = {
				[Op.iLike]: `%${params.f_url}%`,
			};
		}

		if (params.f_parent_title) {
			filterConditions["$parent.title$"] = {
				[Op.iLike]: `%${params.f_parent_title}%`,
			};
		}

		// global search q
		const andConditions = [];
		if (params.q) {
			andConditions.push({
				[Op.or]: [
					{ name: { [Op.iLike]: `%${params.q}%` } },
					{ title: { [Op.iLike]: `%${params.q}%` } },
					{ type: { [Op.iLike]: `%${params.q}%` } },
					{ url: { [Op.iLike]: `%${params.q}%` } },
					{ "$parent.title$": { [Op.iLike]: `%${params.q}%` } },
				],
			});
		}

		const whereClause = {
			...filterConditions,
			...(andConditions.length
				? {
						[Op.and]: andConditions,
				  }
				: {}),
		};

		let menus = [];
		menus = await dbSAPPS.Menu.findAll({
			where: whereClause,
			include: [
				{
					model: dbSAPPS.Menu,
					as: "parent",
					attributes: ["title"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"], // ambil field yang diperlukan
				},
			],
			order: [["modified", "DESC"]],
		});

		// update relation with name
		menus = menus.map((menu) => {
			return {
				...menu.dataValues,
				parent_title: menu?.parent?.title,
				modifier: menu?.modifier?.full_name,
			};
		});

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

/**
 * Get menu hierarchy
 */
async function getMenuHierarchy(params) {
	try {
		// filter
		const filterConditions = {};

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

		const menus = await dbSAPPS.Menu.findAll({
			where: filterConditions,
			include: [
				{
					model: dbSAPPS.Menu,
					as: "parent",
					attributes: ["id", "title"],
				},
			],
			order: [
				["parent_id", "ASC"],
				["order_no", "ASC"],
			],
			raw: true,
			nest: true,
		});

		const buildHierarchy = (items, parentId = null) => {
			return items
				.filter((item) => item.parent_id === parentId)
				.map((item) => {
					let menuItem = {
						id: item.name + "-" + item.id,
						title: item.title,
						type: item.type,
						url: item.url ? item.url : "",
					};

					const children = buildHierarchy(items, item.id);
					if (children.length > 0) {
						menuItem.children = children;
					}

					const icon = item.icon ? item.icon : "";
					if (icon) {
						menuItem.icon = icon;
					}

					if (item.type === "group" || item.type === "collapse" || (item.breadcrumbs === false && item.type === "item")) {
						menuItem.breadcrumbs = false;
					}

					return menuItem;
				});
		};

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

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

		if (params.is_parent) {
			filterConditions.is_parent = {
				// true is always sent as a string from the frontend
				[Op.eq]: params.is_parent,
			};
		}

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

		let options = [];
		options = await dbSAPPS.Menu.findAll({
			attributes: ["id", "name", "title", "type", "icon", "url"],
			where: filterConditions,
			include: [
				{
					model: dbSAPPS.Menu,
					as: "parent",
					attributes: ["id", "title"],
				},
			],
			order: [["order_no", "ASC"]],
		});

		// update relation with name
		options = options.map((option) => {
			return {
				...option.dataValues,
				parent_title: option?.parent?.title,
				modifier: option?.modifier?.full_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
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

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

		const count = await dbSAPPS.Menu.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
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.Menu.findOne({
			where: {
				name: params.name,
				title: params.title,
				type: params.type,
				url: params.url,
				parent_id: params.parent_id,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `is already taken.`,
			};
		}

		// save
		const menu = await dbSAPPS.Menu.create(params, { transaction });
		await menu.update({ order_no: menu.id }, { transaction });

		await transaction.commit();
		return {
			id: menu?.id,
			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
 *
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const menu = await dbSAPPS.Menu.findByPk(id);
		if (!menu) return { success: false, message: "ID not found!" };

		// validate existing
		const existing = await dbSAPPS.Menu.findOne({
			where: {
				name: params.name,
				title: params.title,
				type: params.type,
				url: params.url,
				parent_id: params.parent_id,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `is already taken.`,
			};
		}

		// save
		await menu.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
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const menu = await dbSAPPS.Menu.findByPk(id);
		if (!menu) 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;

		// save
		await menu.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
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const menu = await dbSAPPS.Menu.findByPk(id);
		if (!menu) return { success: false, message: "ID not found!" };

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