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

/** Helper to clean undefined values from an object */
const clean = (obj) => {
	const newObj = {};
	Object.keys(obj).forEach((key) => {
		if (obj[key] !== undefined) newObj[key] = obj[key];
	});
	return newObj;
};

/** Normalize field types for MySQL safety */
const normalize = (data) => {
	const booleans = ["enabled", "breadcrumbs", "is_parent"];
	const integers = ["parent_id", "order_no", "owner", "modified_by"];

	booleans.forEach((f) => {
		if (data[f] !== undefined && data[f] !== null) {
			if (typeof data[f] === "string") data[f] = data[f].toLowerCase() === "true";
			else data[f] = !!data[f];
		}
	});

	integers.forEach((f) => {
		if (data[f] !== undefined && data[f] !== null) {
			if (data[f] === "" || data[f] === "null") data[f] = null;
			else {
				const val = parseInt(data[f], 10);
				data[f] = isNaN(val) ? null : val;
			}
		}
	});

	return data;
};

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) {
	try {
		// 1. Prep and normalize
		const data = normalize(clean(params));
		if (!data.creation) data.creation = new Date();
		data.modified = new Date();
		if (!data.owner) data.owner = 1;
		if (!data.modified_by) data.modified_by = 1;

		// 2. Pre-validate uniqueness outside transaction
		if (data.name) {
			const existing = await dbSAPPS.Menu.findOne({
				where: { name: data.name },
			});
			if (existing) return { success: false, message: `Menu name "${data.name}" is already taken.` };
		}

		// 3. Short transaction only for persistence
		const transaction = await dbSAPPS.sequelize.transaction();
		try {
			const menu = await dbSAPPS.Menu.create(data, { transaction });
			// auto-sequence if order_no not provided
			if (!data.order_no) {
				await menu.update({ order_no: menu.id }, { transaction });
			}
			await transaction.commit();
			return { id: menu.id, success: true, message: "Saved successfully!" };
		} catch (saveError) {
			if (transaction) await transaction.rollback();
			throw saveError;
		}
	} catch (error) {
		console.error("Menu Create Error:", error);
		return { success: false, message: error?.message || "Failed to save!" };
	}
}

/**
 * Updates an existing
 *
 */
async function update(id, params) {
	const pk = parseInt(id, 10);
	if (isNaN(pk)) return { success: false, message: "Invalid ID!" };

	// 1. Fetch outside transaction to reduce lock time
	const menu = await dbSAPPS.Menu.findByPk(pk);
	if (!menu) return { success: false, message: "ID not found!" };

	// 2. Prep and pick allowed fields
	const updateData = normalize(clean(params));

	// 3. Pre-validate duplicate if name changed (Safe for race conditions if name is indexed)
	if (updateData.name && updateData.name !== menu.name) {
		const existing = await dbSAPPS.Menu.findOne({
			where: { name: updateData.name, id: { [Op.ne]: pk } },
		});
		if (existing) return { success: false, message: `Menu name "${updateData.name}" is already taken.` };
	}

	// 4. Robus creation handling
	if (!updateData.creation) {
		if (!menu.creation) updateData.creation = new Date();
		else delete updateData.creation;
	}
	updateData.modified = new Date();
	if (!updateData.modified_by) updateData.modified_by = 1;

	// 5. Short transaction only for the final persistence
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		await menu.update(updateData, { transaction });
		await transaction.commit();
		return { success: true, message: "Saved successfully!" };
	} catch (error) {
		if (transaction) await transaction.rollback();
		console.error("Menu Update Error:", error);
		return { success: false, message: error?.message || "Failed to save!" };
	}
}

/**
 * Enable or disable
 */
async function enabled(id, params) {
	try {
		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;
		updateData.modified = new Date();

		await menu.update(updateData);
		return { success: true, message: "Saved successfully!" };
	} catch (error) {
		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,
		};
	}
}
