import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { readAiUsageLogs } from "@/lib/ai/usage-logger";
import { formatCostUsd } from "@/lib/ai/cost-tracking";

export async function GET(request: Request) {
  try {
    const user = await getSessionUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const limit = Math.min(Number(searchParams.get("limit") ?? 100), 500);
    const postId = searchParams.get("postId")?.trim();

    let logs = await readAiUsageLogs(limit);
    if (postId) {
      logs = logs.filter((l) => l.postId === postId);
    }

    const totalCostUsd = logs.reduce((sum, l) => sum + l.estimatedCostUsd, 0);

    return NextResponse.json({
      logs,
      count: logs.length,
      totalCostUsd,
      totalCostFormatted: formatCostUsd(totalCostUsd),
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Failed to read AI usage logs";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
