import { AuthRequest } from './auth'
import prisma from '../lib/prisma'
import logger from '../lib/logger'

export async function auditLog(
  req: AuthRequest,
  action: string,
  entity: string,
  entityId?: string,
  detail?: Record<string, unknown>,
) {
  if (!req.user) return
  try {
    await prisma.auditLog.create({
      data: {
        orgId: req.user.orgId,
        userId: req.user.id,
        action,
        entity,
        entityId,
        detail: detail ? JSON.parse(JSON.stringify(detail)) : undefined,
        ip: req.ip,
      },
    })
  } catch (err) {
    logger.error({ err, action, entity, entityId }, 'Audit log error')
  }
}
