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

module.exports = (sequelize) => {
	const RoleMenu = sequelize.define(
		"rolemenu",
		{
			role_id: {
				type: DataTypes.INTEGER,
				references: {
					model: "roles",
					key: "id",
				},
				onDelete: "CASCADE",
				primaryKey: true,
			},
			menu_id: {
				type: DataTypes.INTEGER,
				references: {
					model: "menus",
					key: "id",
				},
				onDelete: "CASCADE",
				primaryKey: true,
			},
			// granular permissions per role-menu
			can_create: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
			can_read: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
			can_update: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
			can_delete: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
		},
		{
			tableName: "rolemenus",
			freezeTableName: true,
			indexes: [
				// OPTIMIZATION: Index on role_id for fast menu lookup
				{
					name: "idx_rolemenus_role_id",
					fields: ["role_id"],
				},
				// OPTIMIZATION: Index on menu_id for fast role lookup
				{
					name: "idx_rolemenus_menu_id",
					fields: ["menu_id"],
				},
				// OPTIMIZATION: Composite index for role_id + menu_id queries
				{
					name: "idx_rolemenus_role_menu",
					fields: ["role_id", "menu_id"],
				},
			],
		}
	);

	/**
	 * Define associations for the RoleMenu model.
	 * @param {object} models - The models to associate with.
	 */
	RoleMenu.associate = (models) => {
		/**
		 * Associate RoleMenu with Role
		 * @param {object} models - The models to associate with.
		 * @param {object} models.Role - The Role model.
		 */
		RoleMenu.belongsTo(models.Role, {
			foreignKey: "role_id",
			as: "role",
		});

		/**
		 * Associate RoleMenu with Menu
		 * @param {object} models - The models to associate with.
		 * @param {object} models.Menu - The Menu model.
		 */
		RoleMenu.belongsTo(models.Menu, {
			foreignKey: "menu_id",
			as: "menu",
		});
	};

	return RoleMenu;
};
