/**
 * Append-only audit trail for platform-admin mutations (AuditEvent, actorType ADMIN). Pass the
 * transaction client so the audit row commits or rolls back together with the change it describes.
 * Payloads describe what changed; they never contain passwords or password hashes.
 */
import type { Prisma, PrismaClient } from '@pintrush/db';

type Writer = Pick<PrismaClient, 'auditEvent'> | Prisma.TransactionClient;

export async function adminAudit(
  db: Writer,
  adminId: string,
  type: `admin.${string}`,
  payload: Record<string, unknown>,
  scope: { venueId?: string | null; roomId?: string | null; gameSessionId?: string | null } = {},
): Promise<void> {
  await db.auditEvent.create({
    data: {
      actorType: 'ADMIN',
      actorId: adminId,
      type,
      venueId: scope.venueId ?? null,
      roomId: scope.roomId ?? null,
      gameSessionId: scope.gameSessionId ?? null,
      // JSON round-trip drops undefined fields and turns Dates into ISO strings.
      payload: JSON.parse(JSON.stringify(payload)) as Prisma.InputJsonValue,
    },
  });
}
