module.exports = (sequelize, DataTypes) => {
  const Role = sequelize.define('Role', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Company',
        key: 'id'
      },
      comment: 'NULL for system-wide roles'
    },
    department_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Department',
        key: 'id'
      },
      comment: 'Department this role belongs to'
    },
    role_code: {
      type: DataTypes.STRING(50),
      allowNull: false
    },
    role_name: {
      type: DataTypes.STRING(200),
      allowNull: false
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    is_system_role: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: 'True for system-defined roles (cannot be deleted)'
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    effective_from: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    effective_to: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    }
  }, {
    tableName: 'role',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'role_code']
      },
      {
        fields: ['status']
      },
      {
        fields: ['effective_from', 'effective_to']
      }
    ]
  });

  Role.associate = function(models) {
    Role.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    Role.belongsTo(models.Department, { foreignKey: 'department_id', as: 'department' });
    Role.hasMany(models.UserRole, { foreignKey: 'role_id', as: 'userRoles' });
    Role.belongsToMany(models.User, { through: models.UserRole, foreignKey: 'role_id', as: 'users' });
    Role.hasMany(models.RolePermission, { foreignKey: 'role_id', as: 'rolePermissions' });
    Role.belongsToMany(models.Permission, { through: models.RolePermission, foreignKey: 'role_id', as: 'permissions' });
  };

  return Role;
};

