import { prisma as globalPrisma } from '@/lib/prisma'
import type { Prisma, PrismaClient } from '@prisma/client'

/** Minimal Prisma-like client that supports auditLog.create (works with PrismaClient and transaction clients). */
type AuditPrismaClient = Pick<PrismaClient, 'auditLog'>

/**
 * Shared utility for creating audit log entries.
 * Wrapped in try-catch so audit failures never break the calling operation.
 *
 * @param input.prisma - Optional Prisma client instance. When omitted the global
 *   singleton is used. Pass `ctx.prisma` from tRPC handlers so audit writes
 *   participate in the same transaction when applicable.
 */
export async function logAudit(input: {
  prisma?: AuditPrismaClient
  userId?: string | null
  action: string
  entityType: string
  entityId?: string
  detailsJson?: Record<string, unknown>
  ipAddress?: string
  userAgent?: string
}): Promise<void> {
  try {
    const db = input.prisma ?? globalPrisma
    await db.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)
  }
}
