import type { FastifyRequest } from "fastify";
import { prisma } from "./prisma.js";
import { createId } from "./id.js";

type AuditInput = {
  lawFirmId: string;
  officeId?: string | null;
  actorUserId?: string | null;
  entityType: string;
  entityId?: string | null;
  action: string;
  changeReason?: string | null;
  beforeJson?: unknown;
  afterJson?: unknown;
  request?: FastifyRequest;
};

export async function writeAuditLog(input: AuditInput) {
  await prisma.auditLog.create({
    data: {
      id: createId(),
      law_firm_id: input.lawFirmId,
      office_id: input.officeId ?? null,
      actor_user_id: input.actorUserId ?? null,
      entity_type: input.entityType,
      entity_id: input.entityId ?? null,
      action: input.action,
      change_reason: input.changeReason ?? null,
      before_json: input.beforeJson ?? undefined,
      after_json: input.afterJson ?? undefined,
      ip_address: input.request?.ip ?? null,
      user_agent: input.request?.headers["user-agent"]?.slice(0, 512) ?? null,
    },
  });
}
