import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";

/**
 * GET /api/token/conversations/:id — Load a single conversation with all messages.
 *
 * Auth: NextAuth session required.
 * Returns: { conversation: { id, title, messages: [...] } }
 * Messages ordered by createdAt ASC.
 */
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;

  try {
    const conversation = await db.tokenConversation.findFirst({
      where: { id, userId: session.user.id },
      select: {
        id: true,
        title: true,
        createdAt: true,
        updatedAt: true,
        messages: {
          orderBy: { createdAt: "asc" },
          select: {
            id: true,
            role: true,
            content: true,
            model: true,
            costUsd: true,
            latencyMs: true,
            createdAt: true,
          },
        },
      },
    });

    if (!conversation) {
      return NextResponse.json({ error: "Conversation not found" }, { status: 404 });
    }

    logger.info(
      {
        action: "token_conversation_loaded",
        conversation_id: id,
        message_count: conversation.messages.length,
      },
      "Token conversation loaded",
    );

    return NextResponse.json({ conversation });
  } catch (err) {
    logger.error({ err, action: "token_conversation_load_error", conversation_id: id }, "Failed to load conversation");
    return NextResponse.json(
      { error: "Failed to load conversation" },
      { status: 500 },
    );
  }
}
