import { Prisma, type PrismaClient } from '@prisma/client';
import type { OwnerAuditEntry } from '@nexumi/shared';
import { prisma } from './prisma';

export interface WriteOwnerAuditInput {
  actorUserId: string;
  action: string;
  targetType?: string | null;
  targetId?: string | null;
  before?: unknown;
  after?: unknown;
}

function toJson(value: unknown): Prisma.InputJsonValue | typeof Prisma.JsonNull {
  if (value === undefined || value === null) {
    return Prisma.JsonNull;
  }
  return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue;
}

export async function writeOwnerAudit(
  client: PrismaClient,
  input: WriteOwnerAuditInput
): Promise<void> {
  await client.ownerAuditLog.create({
    data: {
      actorUserId: input.actorUserId,
      action: input.action,
      targetType: input.targetType ?? null,
      targetId: input.targetId ?? null,
      before: toJson(input.before),
      after: toJson(input.after)
    }
  });
}

export async function listOwnerAudit(limit = 50, offset = 0): Promise<OwnerAuditEntry[]> {
  const rows = await prisma.ownerAuditLog.findMany({
    orderBy: { createdAt: 'desc' },
    take: limit,
    skip: offset
  });
  return rows.map((row) => ({
    id: row.id,
    actorUserId: row.actorUserId,
    action: row.action,
    targetType: row.targetType,
    targetId: row.targetId,
    createdAt: row.createdAt.toISOString()
  }));
}
