import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { AuditEvent } from '../common/enums/audit-event.enum'; import { AuditLog, AuditLogDocument } from './schemas/audit-log.schema'; export interface AuditContext { userId?: string; actorId?: string; username?: string; ip?: string; userAgent?: string; metadata?: Record; } /** * Central audit writer — all security-sensitive actions flow through here. */ @Injectable() export class AuditService { constructor( @InjectModel(AuditLog.name) private readonly auditModel: Model, ) {} async log(event: AuditEvent, context: AuditContext = {}): Promise { await this.auditModel.create({ event, userId: context.userId ? new Types.ObjectId(context.userId) : undefined, actorId: context.actorId ? new Types.ObjectId(context.actorId) : undefined, username: context.username, ip: context.ip, userAgent: context.userAgent, metadata: context.metadata ?? {}, }); } }