const mongoose = require('mongoose');

const actionSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    enum: [
      'read',      // View/Read data
      'create',    // Create new records
      'edit',      // Edit/Update records
      'delete',    // Delete records
      'approve',   // Approve items (workflow)
      'reject',    // Reject items (workflow)
      'review',    // Review items (workflow)
      'export',    // Export/Download data
      'import',    // Import data in bulk
      'assign',    // Assign items to users
      'resolve',   // Resolve/Close items
      'schedule',  // Schedule automated actions
      'share'      // Share items with others
    ]
  },
  displayName: {
    type: String,
    required: true
  },
  description: String
}, { _id: false });

const moduleSchema = 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
  },
  icon: {
    type: String,
    default: 'box'
  },
  category: {
    type: String,
    enum: ['crm', 'admin', 'reports', 'settings', 'workflow', 'analytics'],
    default: 'crm'
  },
  route: {
    type: String,
    required: true
  },
  order: {
    type: Number,
    default: 0
  },
  isActive: {
    type: Boolean,
    default: true
  },
  actions: [actionSchema],
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true
});

// Compound indexes (not duplicating unique fields)
moduleSchema.index({ category: 1, order: 1 });
moduleSchema.index({ isActive: 1 });

module.exports = mongoose.model('Module', moduleSchema);