const mongoose = require('mongoose');

const configSchema = new mongoose.Schema({
  userTypes: [{
    code: {
      type: String,
      required: true,
      uppercase: true
    },
    label: {
      type: String,
      required: true
    }
  }],
  rules: [{
    type: String,
    required: true
  }],
  sections: [{
    key: {
      type: String,
      required: true
    },
    title: {
      type: String,
      required: true
    },
    content: {
      type: String,
      default: ''
    }
  }],
  logo: {
    type: String,
    default: null
  },
  appName: {
    type: String,
    default: 'App'
  },
  updatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Admin',
    required: true
  }
}, {
  timestamps: true
});

// Ensure only one config document exists
configSchema.pre('save', async function(next) {
  if (this.isNew) {
    const existing = await this.constructor.findOne();
    if (existing) {
      const error = new Error('Only one configuration document is allowed');
      return next(error);
    }
  }
  next();
});

module.exports = mongoose.model('Config', configSchema);