/**
 * Client Memory Log — tracks every significant interaction per brand
 * for AI context. All calls are fire-and-forget.
 */

import { prisma } from "@/lib/prisma";

export interface MemoryEntry {
  brandId: string;
  userId?: string;
  category: string;
  action: string;
  summary: string;
  details?: Record<string, unknown>;
  aiContext?: string;
}

/**
 * Log a memory entry. Fire-and-forget — never awaited by callers.
 */
export function logMemory(entry: MemoryEntry): void {
  prisma.clientMemory.create({
    data: {
      brandId: entry.brandId,
      userId: entry.userId ?? null,
      category: entry.category,
      action: entry.action,
      summary: entry.summary,
      details: entry.details ? (entry.details as object) : undefined,
      aiContext: entry.aiContext ?? entry.summary,
    },
  }).catch((err) => console.error("[client-memory]", err));
}

/**
 * Get the last N memory entries as a condensed AI context string.
 */
export async function getMemoryContext(brandId: string, limit = 20): Promise<string> {
  const entries = await prisma.clientMemory.findMany({
    where: { brandId },
    orderBy: { timestamp: "desc" },
    take: limit,
    select: { aiContext: true, summary: true, timestamp: true, category: true },
  });

  if (entries.length === 0) return "No previous interactions recorded.";

  return entries.reverse().map((e) => {
    const date = e.timestamp.toLocaleDateString("en-US", { month: "short", day: "numeric" });
    return `- ${date}: ${e.aiContext || e.summary}`;
  }).join("\n");
}

/**
 * Get raw memory entries for display.
 */
export async function getMemoryLog(brandId: string, limit = 50): Promise<Array<{
  id: string; category: string; action: string; summary: string; timestamp: Date; details: unknown;
}>> {
  return prisma.clientMemory.findMany({
    where: { brandId },
    orderBy: { timestamp: "desc" },
    take: limit,
    select: { id: true, category: true, action: true, summary: true, timestamp: true, details: true },
  });
}
