/**
 * Voice Agent Conversations List API
 * GET - Paginated conversation list
 */

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("VoiceAgentConversationsAPI");

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

    const limit = parseInt(
      request.nextUrl.searchParams.get("pageSize") || "20",
      10,
    );

    const result = await convexQuery(
      "voice_agents/queries:getConversationLogs",
      { userId: user.userId, limit },
    );

    return NextResponse.json({
      conversations: result ?? [],
      success: true,
    });
  } catch (error) {
    scopedLogger.error("Failed to get conversations", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
