/**
 * Audit Log API
 * GET - Fetch user's security events and audit log
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { withRateLimit } from "@/lib/rate-limiter";
import { maskIPAddress } from "@/lib/services/session-manager";
import { convexQuery } from "@/lib/convex-client";
import { getAuthenticatedConvexUser } from "@/lib/convex-auth-state";

/**
 * GET /api/user/audit-log
 * Returns audit log events for the current user
 * Supports filtering and pagination
 * Rate limited to 30 requests per 15 minutes
 * Supports both NextAuth sessions and custom auth_token cookies (OTP login)
 */
export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // Rate limiting (bypass in development to avoid HMR issues)
    const isDevelopment = process.env.NODE_ENV === "development";

    if (!isDevelopment) {
      const rateLimitResponse = await applyRateLimit(
        request,
        rateLimiters.authGeneral,
      );
      if (rateLimitResponse) return rateLimitResponse;
    }

    // Get user from Convex
    const user = await convexQuery<ConvexUser>("auth/queries:getUserByEmail", {
      email: userEmail,
    });

    if (!user) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    // Parse query parameters
    const { searchParams } = new URL(request.url);
    const type = searchParams.get("type"); // login, security, profile, billing
    const page = parseInt(searchParams.get("page") || "1");
    const perPage = Math.min(
      parseInt(searchParams.get("perPage") || "20"),
      100,
    );
    const offset = (page - 1) * perPage;

    const result = await convexQuery<{
      events: Array<Record<string, unknown>>;
      total: number;
    }>("auth/queries:getAuditLogs", {
      userId: user.id,
      type,
      limit: perPage,
      offset,
    });

    const events = result?.events ?? [];
    const total = result?.total ?? 0;

    // Format events for response (mask sensitive data)
    const formattedEvents = events.map((event) => ({
      id: event._id,
      type: event.type,
      action: event.action,
      success: event.success,
      ipAddress: maskIPAddress(event.ip),
      timestamp: event.createdAt,
      metadata: event.metadata
        ? {
            ...event.metadata,
            // Remove any sensitive fields from metadata if present
            password: undefined,
            token: undefined,
          }
        : null,
    }));

    return NextResponse.json({
      success: true,
      events: formattedEvents,
      pagination: {
        page,
        perPage,
        total,
        totalPages: Math.ceil(total / perPage),
      },
    });
  } catch (error) {
    console.error("[API] Failed to fetch audit log:", error);
    return NextResponse.json(
      { success: false, error: "Failed to fetch audit log" },
      { status: 500 },
    );
  }
}
