const mongoose = require('mongoose');

const modulePermissionSchema = new mongoose.Schema({
  moduleId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Module',
    required: true
  },
  moduleName: {
    type: String,
    required: true
  },
  permissions: {
    type: Map,
    of: Boolean,
    default: {}
  }
}, { _id: false });

const roleSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,  // This creates an index automatically
    lowercase: true,
    trim: true
  },
  displayName: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  level: {
    type: Number,
    required: true,
    enum: [0, 1, 2, 3],
    default: 3
  },
  scope: {
    type: String,
    enum: ['global', 'company', 'partner'],
    default: 'user'
  },
  isSystemRole: {
    type: Boolean,
    default: false
  },
  isActive: {
    type: Boolean,
    default: true
  },
  modulePermissions: [modulePermissionSchema],
  specialPermissions: [{
    type: String,
    enum: [
      'access_all_companies',
      'manage_roles',
      'view_audit_logs',
      'system_configuration',
      'manage_modules',
      'impersonate_users'
    ]
  }],
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true
});

// Pre-remove hook to prevent deletion of system roles
roleSchema.pre('remove', function(next) {
  if (this.isSystemRole) {
    return next(new Error('System roles cannot be deleted'));
  }
  next();
});

// Compound indexes (not duplicating unique fields)
roleSchema.index({ level: 1, scope: 1 });
roleSchema.index({ isSystemRole: 1 });

module.exports = mongoose.model('Role', roleSchema);