import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";

/**
 * 🔒 CSP VIOLATION REPORTING ENDPOINT
 *
 * This endpoint receives Content Security Policy (CSP) violation reports
 * from browsers when blocked content attempts to load.
 *
 * WHY THIS MATTERS:
 * - Detects XSS attack attempts in real-time
 * - Identifies misconfigured CSP rules that block legitimate content
 * - Provides security monitoring without third-party services
 *
 * EXAMPLE VIOLATION:
 * When an attacker tries to inject <script src="evil.com/steal.js">,
 * the browser blocks it and sends a report here with details.
 */
export async function POST(req: NextRequest) {
  try {
    // Parse the CSP violation report sent by the browser
    const report = await req.json();

    // 🔒 SECURITY LOG: Record all CSP violations for security monitoring
    // This helps identify:
    // 1. Active XSS attack attempts (blocked-uri from suspicious domains)
    // 2. Legitimate resources blocked by overly strict CSP (needs allowlist update)
    // 3. Patterns of attack attempts (same IP, same violation type)
    logger.warn("CSP Violation Detected", {
      type: "csp_violation",
      report: {
        // The policy directive that was violated
        violatedDirective: report["csp-report"]?.["violated-directive"],

        // The URI that was blocked
        blockedUri: report["csp-report"]?.["blocked-uri"],

        // The page where the violation occurred
        documentUri: report["csp-report"]?.["document-uri"],

        // The actual content that was blocked (if available)
        sourceFile: report["csp-report"]?.["source-file"],

        // Line and column number where the violation occurred
        lineNumber: report["csp-report"]?.["line-number"],
        columnNumber: report["csp-report"]?.["column-number"],

        // The original policy that was violated
        originalPolicy: report["csp-report"]?.["original-policy"],
      },

      // Request metadata for investigation
      metadata: {
        ip:
          req.headers.get("x-forwarded-for") ||
          req.headers.get("x-real-ip") ||
          "unknown",
        userAgent: req.headers.get("user-agent") || "unknown",
        timestamp: new Date().toISOString(),
      },
    });

    // Return 204 No Content (success but no response body)
    // This is the standard response for CSP report endpoints
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    // Log parsing errors but don't expose details to client
    logger.error("Failed to process CSP report", {
      error: error instanceof Error ? error.message : "Unknown error",
    });

    // Still return 204 to avoid revealing internal errors to attackers
    return new NextResponse(null, { status: 204 });
  }
}
