module.exports = function (sequelize, DataTypes) {
  const roles = sequelize.define(
    'roles',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

      name: {
        type: DataTypes.TEXT,
        allowNull: false,
        validate: {
          notEmpty: { msg: 'Role name is required' },
          len: {
            args: [1, 100],
            msg: 'Role name must be between 1 and 100 characters',
          },
        },
      },

      role_customization: {
        type: DataTypes.TEXT,
      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  roles.associate = (db) => {
    db.roles.belongsToMany(db.permissions, {
      as: 'permissions',
      foreignKey: {
        name: 'roles_permissionsId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      through: 'rolesPermissionsPermissions',
    });

    db.roles.belongsToMany(db.permissions, {
      as: 'permissions_filter',
      foreignKey: {
        name: 'roles_permissionsId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      through: 'rolesPermissionsPermissions',
    });

    /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity

    db.roles.hasMany(db.users, {
      as: 'users_app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: true,
      onDelete: 'SET NULL',
      onUpdate: 'CASCADE',
    });

    //end loop

    db.roles.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.roles.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };

  return roles;
};
