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

export interface WriteDashboardAuditInput {
  guildId?: string | null;
  actorUserId: string;
  action: string;
  path?: string | null;
  before?: unknown;
  after?: unknown;
}

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

export async function writeDashboardAudit(
  prisma: PrismaClient,
  input: WriteDashboardAuditInput
): Promise<void> {
  await prisma.dashboardAuditLog.create({
    data: {
      guildId: input.guildId ?? null,
      actorUserId: input.actorUserId,
      action: input.action,
      path: input.path ?? null,
      before: toJsonInput(input.before) ?? Prisma.JsonNull,
      after: toJsonInput(input.after) ?? Prisma.JsonNull
    }
  });
}

export async function listRecentDashboardAudit(
  guildId: string,
  limit = 10
): Promise<DashboardAuditEntry[]> {
  const entries = await prisma.dashboardAuditLog.findMany({
    where: { guildId },
    orderBy: { createdAt: 'desc' },
    take: limit
  });

  return entries.map((entry) => ({
    id: entry.id,
    guildId: entry.guildId,
    actorUserId: entry.actorUserId,
    action: entry.action,
    path: entry.path,
    createdAt: entry.createdAt.toISOString()
  }));
}
