/**
 * Voice Agent Analytics API
 * GET - Get aggregated analytics
 */

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

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

    const entries = logs ?? [];

    return NextResponse.json({
      success: true,
      totalCalls: entries.length,
      successRate:
        entries.filter((l) => l.outcome === "success").length /
        Math.max(entries.length, 1),
      conversations: entries,
    });
  } catch (error) {
    scopedLogger.error("Failed to get analytics", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
