/**
 * AuditLog Model
 *
 * Tracks all significant actions in the system: user management,
 * role changes, permission overrides, login activity, etc.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IAuditLog extends Document {
  userId: mongoose.Types.ObjectId;
  userEmail?: string;
  action: string;           // 'user.create', 'role.update', 'permission.override', etc.
  resource: string;         // 'User', 'Role', 'Permission', 'Auth'
  resourceId?: string;
  companyId?: string;
  details?: any;            // Before/after snapshot, or any extra context
  ipAddress?: string;
  userAgent?: string;
  createdAt: Date;
}

const AuditLogSchema = new Schema<IAuditLog>({
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    index: true,
  },
  userEmail: {
    type: String,
    trim: true,
  },
  action: {
    type: String,
    required: [true, 'Action is required'],
    trim: true,
    index: true,
  },
  resource: {
    type: String,
    required: [true, 'Resource is required'],
    trim: true,
    index: true,
  },
  resourceId: {
    type: String,
    trim: true,
  },
  companyId: {
    type: String,
    index: true,
  },
  details: {
    type: Schema.Types.Mixed,
  },
  ipAddress: {
    type: String,
    trim: true,
  },
  userAgent: {
    type: String,
    trim: true,
  },
}, {
  timestamps: true,
});

// Indexes for common queries
AuditLogSchema.index({ action: 1, resource: 1 });
AuditLogSchema.index({ createdAt: -1 });
AuditLogSchema.index({ userId: 1, createdAt: -1 });
AuditLogSchema.index({ companyId: 1, createdAt: -1 });

// TTL index: auto-delete logs older than 1 year
AuditLogSchema.index({ createdAt: 1 }, { expireAfterSeconds: 365 * 24 * 60 * 60 });

export const AuditLog = mongoose.models.AuditLog || mongoose.model<IAuditLog>('AuditLog', AuditLogSchema);