import type { PrismaService } from '../prisma/prisma.service';
import { currentTraceId } from './trace-context';

export interface AuditInput {
  action: string;
  resourceType: string;
  resourceId: string;
  scopeId?: string;
  actorRefId?: string;
  correlationId?: string;
}

/**
 * Write an audit link (P9): binds an action to its trace + actor + resource so a
 * decision can be replayed / a request traced across services. Plain function — reads
 * the current request's trace id from AsyncLocalStorage (no DI). Best-effort: never
 * throws into the caller's happy path.
 */
export async function recordAudit(prisma: PrismaService, input: AuditInput): Promise<void> {
  try {
    await prisma.iiosAuditLink.create({
      data: {
        action: input.action,
        resourceType: input.resourceType,
        resourceId: input.resourceId,
        scopeId: input.scopeId,
        actorRefId: input.actorRefId,
        traceId: currentTraceId(),
        correlationId: input.correlationId ?? currentTraceId(),
      },
    });
  } catch {
    /* audit is best-effort; do not break the request */
  }
}
