/**
 * Sentry Client Configuration
 *
 * Configures Sentry for client-side error tracking in production.
 * Automatically loaded by the Next.js instrumentation system.
 *
 * To enable: set NEXT_PUBLIC_SENTRY_DSN in .env.local
 * Without the DSN, this file is a no-op.
 */

import * as Sentry from "@sentry/nextjs";

const SENTRY_DSN = process.env.NEXT_PUBLIC_SENTRY_DSN;

if (SENTRY_DSN) {
  Sentry.init({
    dsn: SENTRY_DSN,

    // Only enable in production
    enabled: process.env.NODE_ENV === "production",

    // Environment tag
    environment: process.env.NODE_ENV || "development",

    // Performance Monitoring - sample 10% of transactions
    tracesSampleRate: 0.1,

    // Session Replay - sample 10% of sessions, 100% on error
    replaysSessionSampleRate: 0.1,
    replaysOnErrorSampleRate: 1.0,

    // Filter out sensitive data before sending
    beforeSend(event) {
      // Remove PII from requests
      if (event.request) {
        delete event.request.cookies;
        if (event.request.headers) {
          const sensitiveHeaders = [
            "authorization",
            "cookie",
            "x-csrf-token",
          ];
          for (const header of sensitiveHeaders) {
            delete event.request.headers[header];
          }
        }
      }

      // Filter console breadcrumbs that might contain sensitive data
      if (event.breadcrumbs) {
        event.breadcrumbs = event.breadcrumbs.filter((breadcrumb) => {
          if (
            breadcrumb.category === "console" &&
            breadcrumb.level === "log"
          ) {
            return false;
          }
          return true;
        });
      }

      // Attach PostHog error context if available
      try {
        // Dynamic import to avoid circular deps - error-context is client-only
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const { getErrorContext } = require("./lib/error-context");
        const errorContext = getErrorContext();

        if (errorContext.sessionId) {
          event.tags = event.tags || {};
          event.tags.posthog_session_id = errorContext.sessionId;
        }

        event.contexts = event.contexts || {};
        event.contexts.posthog = {
          session_id: errorContext.sessionId,
          session_url: errorContext.sessionUrl,
          distinct_id: errorContext.distinctId,
        };

        if (errorContext.recentActions.length > 0) {
          event.contexts.user_actions = {
            recent: errorContext.recentActions,
            count: errorContext.recentActions.length,
          };
        }
      } catch {
        // Don't let error context failures break error reporting
      }

      return event;
    },

    // Ignore common non-actionable errors
    ignoreErrors: [
      // Browser extensions
      "top.GLOBALS",
      "originalCreateNotification",
      "canvas.contentDocument",
      "MyApp_RemoveAllHighlights",
      "atomicFindClose",

      // Chunk loading (deployment boundary)
      "ChunkLoadError",
      "Loading chunk",
      "Failed to load chunk",

      // Hydration (usually cosmetic)
      "Hydration failed",
      "There was an error while hydrating",
      "Text content does not match server-rendered HTML",

      // Network errors (handled by retry logic)
      "NetworkError",
      "Network request failed",
      "Failed to fetch",
      "Load failed",

      // ResizeObserver (benign browser limitation)
      "ResizeObserver loop limit exceeded",
      "ResizeObserver loop completed with undelivered notifications",
    ],

    // Integrations
    integrations: [
      Sentry.browserTracingIntegration({
        tracePropagationTargets: [
          "localhost",
          /^https:\/\/mawidi\.com/,
          /^https:\/\/.*\.mawidi\.com/,
        ],
      }),
      Sentry.replayIntegration({
        maskAllText: true,
        blockAllMedia: true,
      }),
    ],
  });
}

export {};
