import mongoose from 'mongoose'

const paymentSchema = new mongoose.Schema(
  {
    memberId: { type: mongoose.Schema.Types.ObjectId, ref: 'Member', required: true, index: true },
    helcimTransactionId: { type: String, required: true, unique: true },
    helcimCustomerId: { type: String, index: true },
    helcimSubscriptionId: { type: String, index: true, default: null },

    amount: { type: Number, required: true, min: 0 },
    currency: { type: String, default: 'CAD' },
    paymentDate: { type: Date, required: true },

    paymentType: { type: String, enum: ['monthly', 'annual'], required: true },
    status: { type: String, enum: ['success', 'failed', 'refunded'], required: true, default: 'success' },
    failureReason: { type: String, default: null },

    receiptIssued: { type: Boolean, default: false },
    receiptId: { type: String, default: null },

    rawHelcim: { type: mongoose.Schema.Types.Mixed, default: null },
  },
  { timestamps: true, collection: 'payments' }
)

paymentSchema.index({ memberId: 1, paymentDate: -1 })

export default mongoose.models.Payment || mongoose.model('Payment', paymentSchema)
