import { requireAuth, type JWTContents } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const runtime = "nodejs";

export async function GET(
  request: Request,
  { params }: { params: Promise<{ userId: string }> }
) {
  try {
    const user = await requireAuth(request);
    if (!user) {
      return Response.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { userId } = await params;

    // Verify the requested userId matches the authenticated user
    if (user.userId !== userId) {
      return Response.json({ error: "Forbidden" }, { status: 403 });
    }

    const messages = await prisma.chatHistory.findMany({
      where: { userId },
      orderBy: { createdAt: "desc" },
      take: 50,
    });

    // Return in chronological order
    const ordered = messages.reverse();

    return Response.json({
      messages: ordered.map((m) => ({
        id: m.id,
        role: m.role,
        content: m.content,
        metadata: m.metadata ? JSON.parse(m.metadata) : null,
        createdAt: m.createdAt.toISOString(),
      })),
    });
  } catch (error) {
    console.error("Chat history error:", error);
    return Response.json({ error: "Internal server error" }, { status: 500 });
  }
}
