import mongoose, { Schema, Document, Model } from 'mongoose';

export interface IAuditLog extends Document {
  actorId: mongoose.Types.ObjectId; // References User
  action: string; // e.g. 'USER_LOGIN', 'MEMBER_TRANSFER', 'ATTENDANCE_CORRECT'
  entityType: 'User' | 'Member' | 'Satsang' | 'SatsangSchedule' | 'Attendance' | 'Geography' | 'SystemSettings' | 'Announcement' | 'ImportBatch';
  entityId: mongoose.Types.ObjectId;
  changedFields?: Record<string, { old: any; new: any }>; // Auditing diffs only
  ipAddress?: string;
  timestamp: Date;
}

const AuditLogSchema = new Schema<IAuditLog>({
  actorId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  action: { type: String, required: true, trim: true },
  entityType: {
    type: String,
    enum: ['User', 'Member', 'Satsang', 'SatsangSchedule', 'Attendance', 'Geography', 'SystemSettings', 'Announcement', 'ImportBatch'],
    required: true
  },
  entityId: { type: Schema.Types.ObjectId, required: true },
  changedFields: { type: Map, of: Schema.Types.Mixed }, // Key-value map of changed fields
  ipAddress: { type: String, trim: true },
  timestamp: { type: Date, default: Date.now, required: true }
});

AuditLogSchema.index({ timestamp: -1 });
AuditLogSchema.index({ entityId: 1 });

export const AuditLog: Model<IAuditLog> =
  mongoose.models.AuditLog || mongoose.model<IAuditLog>('AuditLog', AuditLogSchema);
export default AuditLog;
