/**
 * Analytics Events API
 *
 * Receives and stores analytics events from client-side tracking.
 */

import { NextRequest, NextResponse } from "next/server";
import { EventName, EventCategory } from "@/lib/analytics/events";
import { rateLimiters, applyRateLimit } from "@/lib/rate-limiter";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import { getDataSource } from "@/lib/data-source";
export async function GET(req: NextRequest) {
  if (getDataSource("analytics") === "convex") {
    try {
      const { convexQuery } = await import("@/lib/convex-client");
      const searchParams = req.nextUrl.searchParams;
      const userId = req.headers.get("x-user-id") ?? "";
      const category = searchParams.get("category") ?? undefined;
      const result = await convexQuery("analytics/queries:getEvents", {
        userId,
        ...(category && { category }),
        limit: 100,
      });
      if (result !== null) {
        return NextResponse.json({ events: result, success: true });
      }
    } catch (error) {
      console.error("Error fetching events:", error);
    }
  }
  return NextResponse.json({ events: [], success: true });
}

export async function POST(req: NextRequest) {
  try {
    // Rate limiting - use authGeneral rate limiter
    const rateLimitResult = await applyRateLimit(req, rateLimiters.authGeneral);
    if (rateLimitResult) {
      return rateLimitResult;
    }

    // Parse request body
    const body = await req.json();
    const { eventName, category, properties } = body;

    // Validate required fields
    if (!eventName || !category) {
      return NextResponse.json(
        { error: "Missing required fields: eventName, category" },
        { status: 400 },
      );
    }

    // Validate event name is valid
    if (!Object.values(EventName).includes(eventName)) {
      return NextResponse.json(
        { error: "Invalid event name" },
        { status: 400 },
      );
    }

    // Validate category is valid
    if (!Object.values(EventCategory).includes(category)) {
      return NextResponse.json(
        { error: "Invalid event category" },
        { status: 400 },
      );
    }

    // Convex branch — track event in Convex instead of Prisma
    if (getDataSource("analytics") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("analytics/mutations:trackEvent", {
          eventName: eventName as string,
          category: category as string,
          properties: properties as Record<string, unknown>,
        });
        return NextResponse.json({ success: true }, { status: 200 });
      } catch (error) {
        console.error("Error tracking event:", error);
        return NextResponse.json(
          { error: "Failed to track event" },
          { status: 500 },
        );
      }
    }

    return NextResponse.json({ success: true }, { status: 200 });
  } catch (error) {
    console.error("Error tracking event:", error);
    return NextResponse.json(
      { error: "Failed to track event" },
      { status: 500 },
    );
  }
}
