import { NextRequest, NextResponse } from "next/server";
import { getDataSource } from "@/lib/data-source";

/**
 * Web Vitals Analytics Endpoint
 * Receives performance metrics from client-side monitoring
 */
export async function POST(request: NextRequest) {
  try {
    const metrics = await request.json();

    // Log metrics in development
    if (process.env.NODE_ENV === "development") {
      console.log("📊 Web Vitals Received:", {
        name: metrics.name,
        value: metrics.value,
        rating: metrics.rating,
        navigationType: metrics.navigationType,
      });
    }

    // Convex branch — persist web vital in Convex
    if (getDataSource("analytics") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("analytics/mutations:recordWebVital", {
          name: metrics.name as string,
          value: metrics.value as number,
          rating: metrics.rating as "good" | "needs-improvement" | "poor",
          url: (metrics.url ?? request.nextUrl.pathname) as string,
          userAgent: request.headers.get("user-agent") ?? undefined,
          navigationType: metrics.navigationType as string | undefined,
        });
        return NextResponse.json({ success: true });
      } catch {
        // Fall through to default handler
      }
    }

    // In production, you could:
    // - Send to analytics service (Google Analytics, Vercel Analytics, etc.)
    // - Store in database for historical tracking
    // - Trigger alerts if metrics exceed thresholds
    // - Aggregate metrics for dashboards

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error processing web vitals:", error);
    return NextResponse.json(
      { error: "Failed to process metrics" },
      { status: 500 },
    );
  }
}
