const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  bookTitle: {
    type: String,
    required: true
  },
  bookCategory: {
    type: String,
    required: true,
    enum: [
      'Textbook', 'Story Book', 'Novel', 'Poetry', 'Drama',
      'Science', 'Math', 'History', 'Geography', 'Religion',
      'Dictionary', 'Encyclopedia', 'Magazine', 'Other'
    ]
  },
  authorName: {
    type: String,
    required: true
  },
  publisher: {
    type: String
  },
  edition: {
    type: String
  },
  publicationYear: {
    type: Number
  },
  quantity: {
    type: Number,
    required: true,
    default: 1,
    min: 0
  },
  availableQuantity: {
    type: Number,
    default: 1,
    min: 0
  },
  description: {
    type: String
  },
  bookImage: {
    type: String  // Path to uploaded book image
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Admin'
  }
}, {
  timestamps: true
});

// Update available quantity before saving
bookSchema.pre('save', function(next) {
  // Set available quantity to total quantity if not provided
  if (this.isNew && !this.availableQuantity) {
    this.availableQuantity = this.quantity;
  }
  next();
});

module.exports = mongoose.model('Book', bookSchema);