import mongoose, { Schema, Document } from 'mongoose';

export interface IAuditLogDocument extends Document {
  // _id is handled by Mongoose
  userId: mongoose.Types.ObjectId;
  action: 'CREATE' | 'UPDATE' | 'DELETE' | 'LOGIN' | 'APPROVE' | 'SYSTEM_CONFIG' | 'EXPORT' | 'SYNC';
  targetCollection: string;
  targetId?: string;
  timestamp: Date;
  details: string;
  ipAddress?: string;
  userAgent?: string;
  createdAt: Date;
}

const auditLogSchema = new Schema<IAuditLogDocument>(
  {
    userId: {
      type: Schema.Types.Mixed, // Accept both ObjectId and string
      ref: 'User',
      required: true
    },
    action: {
      type: String,
      enum: ['CREATE', 'UPDATE', 'DELETE', 'LOGIN', 'APPROVE', 'SYSTEM_CONFIG', 'EXPORT', 'SYNC'],
      required: true,
    },
    targetCollection: { type: String, required: true },
    targetId: String,
    timestamp: { type: Date, default: Date.now },
    details: { type: String, required: true },
    ipAddress: String,
    userAgent: String,
  },
  {
    timestamps: true,
    strict: false, // Allow additional fields
  }
);

auditLogSchema.index({ userId: 1 });
auditLogSchema.index({ action: 1 });
auditLogSchema.index({ targetCollection: 1 });
auditLogSchema.index({ timestamp: -1 });
auditLogSchema.index({ createdAt: -1 });

export const AuditLog = mongoose.model<IAuditLogDocument>('AuditLog', auditLogSchema);
