import mongoose from 'mongoose';

const studentPaymentSchema = new mongoose.Schema(
  {
    student: { type: mongoose.Schema.Types.ObjectId, ref: 'Student', required: true },
    amount: { type: Number, required: true, min: 0 },
    paymentType: {
      type: String,
      enum: ['tuition', 'transport', 'library', 'exam', 'uniform', 'other'],
      default: 'tuition',
    },
    paymentMethod: {
      type: String,
      enum: ['cash', 'card', 'bank_transfer', 'online'],
      default: 'cash',
    },
    status: {
      type: String,
      enum: ['pending', 'completed', 'failed', 'refunded'],
      default: 'completed',
    },
    receiptNumber: { type: String, unique: true, sparse: true },
    paidAt: { type: Date, default: Date.now },
    term: { type: String, default: 'Term 1' },
    academicYear: { type: String, default: '' },
    notes: { type: String, default: '' },
    recordedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  },
  { timestamps: true }
);

studentPaymentSchema.pre('save', async function (next) {
  if (!this.receiptNumber) {
    const count = await mongoose.model('StudentPayment').countDocuments();
    this.receiptNumber = `RCP-${Date.now().toString(36).toUpperCase()}-${String(count + 1).padStart(4, '0')}`;
  }
  next();
});

export default mongoose.model('StudentPayment', studentPaymentSchema);
