import { getDB } from '../db.js';
import { createLogger } from '../diagnostics/logger.js';
const logger = createLogger('audit');
/** Record an audit log event. */
export async function logEvent(event) {
    try {
        const db = getDB();
        await db.auditLog.create({
            data: {
                event: event.event,
                userId: event.userId ?? null,
                ipAddress: event.ipAddress ?? null,
                userAgent: event.userAgent ?? null,
                details: event.details ?? null,
            },
        });
    }
    catch (err) {
        // Fail open — audit logging should never block the primary operation,
        // but still surface the failure so the operator can fix it.
        if (process.env.NODE_ENV !== 'test') {
            logger.error('logEvent failed', { reason: err instanceof Error ? err.message : String(err) });
        }
    }
}
/** Query audit log entries with filters and pagination. */
export async function getAuditLog(options = {}) {
    const db = getDB();
    const { userId, event, page = 1, pageSize = 50 } = options;
    const where = {};
    if (userId)
        where.userId = userId;
    if (event)
        where.event = event;
    const [entries, total] = await Promise.all([
        db.auditLog.findMany({
            where,
            orderBy: { timestamp: 'desc' },
            skip: (page - 1) * pageSize,
            take: pageSize,
        }),
        db.auditLog.count({ where }),
    ]);
    return { entries, total };
}
//# sourceMappingURL=audit.js.map