import mongoose from 'mongoose'; const eventSchema = new mongoose.Schema({ // Multi-tenant support tenantId: { type: mongoose.Schema.Types.ObjectId, ref: 'Tenant', required: true, index: true }, id: { type: String, required: true, unique: true, index: true }, type: { type: String, required: true, index: true }, accountId: { type: String, required: true, index: true }, userId: { type: String, index: true }, sessionId: { type: String, index: true }, action: { type: String, required: true, index: true }, target: String, value: Number, metadata: { type: Map, of: mongoose.Schema.Types.Mixed }, properties: { type: Map, of: mongoose.Schema.Types.Mixed }, timestamp: { type: Date, required: true, index: true } }, { timestamps: true, timeseries: { timeField: 'timestamp', metaField: 'metadata', granularity: 'seconds' } }); // Compound indexes for common queries eventSchema.index({ accountId: 1, timestamp: -1 }); eventSchema.index({ accountId: 1, type: 1, timestamp: -1 }); eventSchema.index({ accountId: 1, userId: 1, timestamp: -1 }); eventSchema.index({ type: 1, action: 1, timestamp: -1 }); // TTL index to auto-delete old events after 1 year eventSchema.index({ timestamp: 1 }, { expireAfterSeconds: 31536000 }); // Multi-tenant indexes eventSchema.index({ tenantId: 1, accountId: 1, timestamp: -1 }); eventSchema.index({ tenantId: 1, accountId: 1, type: 1, timestamp: -1 }); eventSchema.index({ tenantId: 1, accountId: 1, userId: 1, timestamp: -1 }); eventSchema.index({ tenantId: 1, type: 1, action: 1, timestamp: -1 }); eventSchema.index({ tenantId: 1, timestamp: 1 }, { expireAfterSeconds: 31536000 }); export const Event = mongoose.model('Event', eventSchema);