import { Prisma } from "@prisma/client";

import { prisma } from "@/lib/prisma";

type AuditTrailInput = {
  userId?: string | bigint | null;
  action: string;
  entityType: string;
  entityId?: string | bigint | null;
  method: string;
  pathname: string;
  statusCode: number;
  summary?: string | null;
  metadata?: Prisma.InputJsonValue | null;
};

export async function createAuditTrail(input: AuditTrailInput) {
  await prisma.auditTrail.create({
    data: {
      userId:
        input.userId === undefined || input.userId === null
          ? null
          : BigInt(input.userId),
      action: input.action,
      entityType: input.entityType,
      entityId: input.entityId === undefined || input.entityId === null ? null : String(input.entityId),
      method: input.method,
      pathname: input.pathname,
      statusCode: input.statusCode,
      summary: input.summary ?? null,
      metadata: input.metadata ?? Prisma.JsonNull
    }
  });
}

export async function createAuditTrailSafe(input: AuditTrailInput) {
  try {
    await createAuditTrail(input);
  } catch (error) {
    console.error("AUDIT_TRAIL_WRITE_FAILED", error);
  }
}
