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

module.exports = (sequelize) => {
	const Role = sequelize.define(
		"role",
		{
			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 },

			// main
			name: { type: DataTypes.STRING(50), allowNull: false },
			display_name: { type: DataTypes.STRING(50), allowNull: false },
			description: { type: DataTypes.TEXT, allowNull: true },
			access_read_all_data: { type: DataTypes.BOOLEAN, allowNull: true },
			administrator_of_hr: { type: DataTypes.BOOLEAN, allowNull: true },
			administrator_of_msd: { type: DataTypes.BOOLEAN, allowNull: true },
			administrator_of_pirlo: { type: DataTypes.BOOLEAN, allowNull: true },
			administrator_of_qmr: { type: DataTypes.BOOLEAN, allowNull: true },
			administrator_of_fat: { type: DataTypes.BOOLEAN, allowNull: true },
			administrator_of_health: { type: DataTypes.BOOLEAN, allowNull: true },

			// fk
			company_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
				references: {
					model: "companies",
					key: "id",
				},
			},
		},
		{
			tableName: "roles",
			freezeTableName: true,
		}
	);

	Role.associate = (models) => {
		Role.hasMany(models.User, { foreignKey: "role_id", as: "users" });
		Role.hasMany(models.Permission, { foreignKey: "role_id", as: "permissions" });
		// Role.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
		Role.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
		Role.belongsToMany(models.Menu, { through: models.RoleMenu, as: "menus", foreignKey: "role_id", otherKey: "menu_id" });
		Role.belongsToMany(models.DocType, { through: models.Permission, foreignKey: "role_id", as: "doctypes" });
	};

	return Role;
};
