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

module.exports = (sequelize) => {
	const Permission = sequelize.define(
		"permission",
		{
			id: {
				type: DataTypes.INTEGER,
				autoIncrement: true,
				primaryKey: true,
			},
			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 },

			// data visibility scope (OWN / ALL / TERRITORY / DESIGNATION / etc.)
			scope: {
				type: DataTypes.STRING(32),
				allowNull: false,
				defaultValue: "ALL",
			},

			// fk
			role_id: {
				type: DataTypes.INTEGER,
				references: {
					model: "roles",
					key: "id",
				},
				onDelete: "CASCADE",
				primaryKey: true,
			},
			doctype_id: {
				type: DataTypes.INTEGER,
				references: {
					model: "docTypes",
					key: "id",
				},
				onDelete: "CASCADE",
				primaryKey: true,
			},
		},
		{
			tableName: "permissions",
			freezeTableName: true,
		}
	);

	/**
	 * Associates the Permission model with other models.
	 * @param {object} models - The models to associate with.
	 * @description
	 *   - A Permission belongs to a Role.
	 *   - A Permission belongs to a DocType.
	 */
	Permission.associate = (models) => {
		/**
		 * Associates the Permission model with the Role model.
		 * Defines a many-to-one relationship between Permission and Role.
		 * @param {object} models - The models to associate with.
		 */
		Permission.belongsTo(models.Role, { foreignKey: "role_id", as: "role" });

		/**
		 * Associates the Permission model with the DocType model.
		 * Defines a many-to-one relationship between Permission and DocType.
		 * @param {object} models - The models to associate with.
		 */
		Permission.belongsTo(models.DocType, { foreignKey: "doctype_id", as: "doctype" });
	};

	return Permission;
};
