import { prisma } from '@/lib/prisma'
import type { Prisma } from '@prisma/client'

/**
 * Shared utility for creating audit log entries.
 * Wrapped in try-catch so audit failures never break the calling operation.
 */
export async function logAudit(input: {
  userId?: string | null
  action: string
  entityType: string
  entityId?: string
  detailsJson?: Record<string, unknown>
  ipAddress?: string
  userAgent?: string
}): Promise<void> {
  try {
    await prisma.auditLog.create({
      data: {
        userId: input.userId ?? null,
        action: input.action,
        entityType: input.entityType,
        entityId: input.entityId,
        detailsJson: input.detailsJson as Prisma.InputJsonValue ?? undefined,
        ipAddress: input.ipAddress,
        userAgent: input.userAgent,
      },
    })
  } catch (error) {
    // Never break the calling operation on audit failure
    console.error('[Audit] Failed to create audit log entry:', error)
  }
}
