import { prisma } from "./db";

const SKIP_FIELDS = new Set([
  "id", "createdAt", "updatedAt", "rawOcrResponse",
  "frontImagePath", "backImagePath", "sourceFile", "mondayItemId",
]);

type FieldChange = { field: string; from: string | null; to: string | null };

export function diffCardFields(
  oldCard: Record<string, unknown>,
  newCard: Record<string, unknown>
): FieldChange[] {
  const changes: FieldChange[] = [];
  const allKeys = new Set([...Object.keys(oldCard), ...Object.keys(newCard)]);

  for (const key of allKeys) {
    if (SKIP_FIELDS.has(key)) continue;
    const oldVal = normalize(oldCard[key]);
    const newVal = normalize(newCard[key]);
    if (oldVal !== newVal) {
      changes.push({ field: key, from: oldVal, to: newVal });
    }
  }

  return changes;
}

function normalize(v: unknown): string | null {
  if (v === null || v === undefined) return null;
  if (typeof v === "object") return JSON.stringify(v);
  return String(v);
}

export async function logActivity(
  cardId: string,
  action: string,
  source: string,
  summary: string,
  changes?: FieldChange[] | null,
  userId?: string | null
) {
  try {
    await prisma.activityLog.create({
      data: {
        cardId,
        action,
        source,
        summary,
        changes: changes && changes.length > 0 ? changes : undefined,
        userId: userId ?? undefined,
      },
    });
  } catch (err) {
    console.error("[activity-log] Failed to create entry:", err);
  }
}

export async function getCardActivity(cardId: string) {
  return prisma.activityLog.findMany({
    where: { cardId },
    orderBy: { createdAt: "desc" },
  });
}
