import { usePrisma } from "../../utils/prisma";

/**
 * GET /api/coach/history
 * Lädt den gespeicherten Chat-Verlauf (nur Pro/Legend).
 * Gibt das neueste CoachSession-Dokument zurück.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  console.log("[coach/history] userId:", user.id);

  const db = usePrisma();

  const profile = await db.profile.findUnique({
    where: { id: user.id },
    select: { plan: true },
  });
  console.log("[coach/history] plan:", profile?.plan);

  if (!profile || !["pro", "legend"].includes(profile.plan)) {
    return { messages: [] };
  }

  const session = await db.coachSession.findFirst({
    where: { userId: user.id },
    orderBy: { createdAt: "desc" },
  });
  console.log(
    "[coach/history] session found:",
    !!session,
    "msgs:",
    Array.isArray(session?.content) ? (session.content as any[]).length : 0,
  );

  if (!session) {
    return { messages: [] };
  }

  return {
    messages: session.content as Array<{ role: string; content: string }>,
  };
});
