import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';

export type AuditEventDocument = AuditEvent & Document;

@Schema({ timestamps: true, collection: 'audit_events' })
export class AuditEvent {
  @Prop({ required: true, unique: true, index: true })
  event_id: string;

  @Prop({ required: true, index: true })
  event_name: string;

  @Prop({ required: true })
  event_version: number;

  @Prop({ required: true, index: true })
  timestamp: Date;

  @Prop({ required: true, enum: ['web', 'api', 'mobile'], index: true })
  source: 'web' | 'api' | 'mobile';

  @Prop({ required: true, index: true })
  actor_id: string;

  @Prop({ required: true, enum: ['advisor', 'client', 'unknown'], index: true })
  actor_role: 'advisor' | 'client' | 'unknown';

  @Prop({ required: true, index: true })
  session_id: string;

  @Prop({ required: true, index: true })
  correlation_id: string;

  @Prop({ type: MongooseSchema.Types.Mixed, default: {} })
  metadata: Record<string, unknown>;
}

export const AuditEventSchema = SchemaFactory.createForClass(AuditEvent);

AuditEventSchema.index({ createdAt: 1 }, { expireAfterSeconds: 63_072_000 });
AuditEventSchema.index({ actor_id: 1, timestamp: -1 });
AuditEventSchema.index({ 'metadata.client_uuid': 1, timestamp: -1 });
AuditEventSchema.index({ correlation_id: 1, timestamp: -1 });
AuditEventSchema.index({ event_name: 1, timestamp: -1 });
