// models/Marks.js
const mongoose = require('mongoose');

const marksSchema = new mongoose.Schema({
  // Student Information
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student',
    required: true
  },
  studentName: {
    type: String,
    required: true
  },
  rollNo: {
    type: String,
    required: true
  },
  
  // Gender Information
  gender: {
    type: String,
    enum: ['Male', 'Female', 'Other'],
    required: true
  },
  
  // Class Information
  className: {
    type: String,
    required: true
  },
  section: {
    type: String,
    default: ''
  },
  
  // Exam Information
  examName: {
    type: String,
    required: true
  },
  examDate: {
    type: Date,
    required: true,
    default: Date.now
  },
  
  // Month Information
  month: {
    type: String,
    required: true,
    enum: [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ]
  },
  
  // Marks Information
  subjectName: {
    type: String,
    required: true
  },
  totalMarks: {
    type: Number,
    required: true,
    min: 0
  },
  obtainedMarks: {
    type: Number,
    required: true,
    min: 0
  },
  
  // Status
  isAbsent: {
    type: Boolean,
    default: false
  },
  
  // Message Field
  message: {
    type: String,
    default: ''
  },
  
  // Additional Info
  remarks: String,
  
  // Created by
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Admin'
  },
  
  // Timestamps
  createdAt: {
    type: Date,
    default: Date.now
  }
});

// Calculate percentage virtual field
marksSchema.virtual('percentage').get(function() {
  if (this.isAbsent) return 0;
  return ((this.obtainedMarks / this.totalMarks) * 100).toFixed(2);
});

// Calculate grade virtual field
marksSchema.virtual('grade').get(function() {
  if (this.isAbsent) return 'AB';
  const percentage = (this.obtainedMarks / this.totalMarks) * 100;
  
  if (percentage >= 80) return 'A+';
  if (percentage >= 70) return 'A';
  if (percentage >= 60) return 'A-';
  if (percentage >= 50) return 'B';
  if (percentage >= 40) return 'C';
  if (percentage >= 33) return 'D';
  return 'F';
});

// Ensure virtuals are included in JSON output
marksSchema.set('toJSON', { virtuals: true });
marksSchema.set('toObject', { virtuals: true });

// Index for better query performance (updated to include month)
marksSchema.index({ studentId: 1, examName: 1, examDate: 1, subjectName: 1, month: 1 }, { unique: true });

const Marks = mongoose.model('Marks', marksSchema);
module.exports = Marks;