const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
	const Menu = sequelize.define(
		"menu",
		{
			id: {
				type: DataTypes.INTEGER,
				autoIncrement: true,
				primaryKey: true,
			},
			creation: { type: DataTypes.DATE, allowNull: false },
			modified: { type: DataTypes.DATE, allowNull: false },
			modified_by: { type: DataTypes.INTEGER, allowNull: false },
			owner: { type: DataTypes.INTEGER, allowNull: false },
			enabled: { type: DataTypes.BOOLEAN, allowNull: false },

			name: { type: DataTypes.STRING(50), allowNull: false },
			title: { type: DataTypes.STRING(100), allowNull: false },
			title_id_word: { type: DataTypes.STRING(200), allowNull: true },
			type: { type: DataTypes.STRING(20), allowNull: false },
			icon: { type: DataTypes.TEXT, allowNull: true },
			url: { type: DataTypes.TEXT, allowNull: true },
			breadcrumbs: { type: DataTypes.BOOLEAN, allowNull: true },
			is_parent: { type: DataTypes.BOOLEAN, allowNull: true },
			order_no: { type: DataTypes.INTEGER, allowNull: true },
			caption: { type: DataTypes.STRING(150), allowNull: true },

			// fk
			parent_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "menus",
			freezeTableName: true,
			indexes: [
				// OPTIMIZATION: Index on enabled for fast filtering
				{
					name: "idx_menus_enabled",
					fields: ["enabled"],
				},
				// OPTIMIZATION: Index on parent_id for hierarchy queries
				{
					name: "idx_menus_parent_id",
					fields: ["parent_id"],
				},
				// OPTIMIZATION: Composite index for enabled + parent_id + order_no
				{
					name: "idx_menus_enabled_parent_order",
					fields: ["enabled", "parent_id", "order_no"],
				},
			],
		}
	);

	Menu.belongsTo(Menu, { as: "parent", foreignKey: "parent_id" });

	Menu.associate = (models) => {
		Menu.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
		Menu.belongsToMany(models.Role, { through: models.RoleMenu, as: "roles", foreignKey: "menu_id", otherKey: "role_id" });
	};

	return Menu;
};
