/**
 * Voice Agent Conversation Detail API
 * GET - Full conversation with transcript
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { convexQuery } from "@/lib/convex-client";

const scopedLogger = logger.scope("VoiceAgentConversationDetailAPI");

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const { id } = await params;

    const logs = (await convexQuery(
      "voice_agents/queries:getConversationLogs",
      { userId: user.userId },
    )) as Array<Record<string, unknown>> | null;

    const log = (logs ?? []).find((l) => l._id === id);
    if (!log) {
      return NextResponse.json(
        { success: false, error: "Conversation not found" },
        { status: 404 },
      );
    }

    return NextResponse.json({ success: true, conversation: log });
  } catch (error) {
    scopedLogger.error("Failed to get conversation detail", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
