// src/services/sentry.client.ts
/**
 * Sentry SDK initialization for client-side error tracking.
 * Implements ADR-015: Application Performance Monitoring and Error Tracking.
 *
 * This module configures @sentry/react to send errors to our self-hosted
 * Bugsink instance, which is Sentry-compatible.
 *
 * IMPORTANT: This module should be imported and initialized at the very top
 * of index.tsx, before any other imports, to ensure all errors are captured.
 */
import * as Sentry from '@sentry/react';
import config from '../config';
import { logger } from './logger.client';

/** Whether Sentry is properly configured (DSN present and enabled) */
export const isSentryConfigured = !!config.sentry.dsn && config.sentry.enabled;

/**
 * Initializes the Sentry SDK for the browser.
 * Should be called once at application startup.
 */
export function initSentry(): void {
  if (!isSentryConfigured) {
    logger.info('[Sentry] Error tracking disabled (VITE_SENTRY_DSN not configured)');
    return;
  }

  Sentry.init({
    dsn: config.sentry.dsn,
    environment: config.sentry.environment,
    debug: config.sentry.debug,

    // Performance monitoring - disabled for now to keep it simple
    tracesSampleRate: 0,

    // Capture console.error as breadcrumbs
    integrations: [
      Sentry.breadcrumbsIntegration({
        console: true,
        dom: true,
        fetch: true,
        history: true,
        xhr: true,
      }),
    ],

    // Filter out development-only errors and noise
    beforeSend(event) {
      // Skip errors from browser extensions
      if (
        event.exception?.values?.[0]?.stacktrace?.frames?.some((frame) =>
          frame.filename?.includes('extension://'),
        )
      ) {
        return null;
      }
      return event;
    },
  });

  logger.info(`[Sentry] Error tracking initialized (${config.sentry.environment})`);
}

/**
 * Captures an exception and sends it to Sentry.
 * Use this for errors that are caught and handled gracefully.
 */
export function captureException(
  error: Error,
  context?: Record<string, unknown>,
): string | undefined {
  if (!isSentryConfigured) {
    return undefined;
  }

  if (context) {
    Sentry.setContext('additional', context);
  }

  return Sentry.captureException(error);
}

/**
 * Captures a message and sends it to Sentry.
 * Use this for non-exception events that should be tracked.
 */
export function captureMessage(
  message: string,
  level: Sentry.SeverityLevel = 'info',
): string | undefined {
  if (!isSentryConfigured) {
    return undefined;
  }

  return Sentry.captureMessage(message, level);
}

/**
 * Sets the user context for all subsequent events.
 * Call this after user authentication.
 */
export function setUser(user: { id: string; email?: string; username?: string } | null): void {
  if (!isSentryConfigured) {
    return;
  }

  Sentry.setUser(user);
}

/**
 * Adds a breadcrumb to the current scope.
 * Breadcrumbs are logged actions that led up to an error.
 */
export function addBreadcrumb(breadcrumb: Sentry.Breadcrumb): void {
  if (!isSentryConfigured) {
    return;
  }

  Sentry.addBreadcrumb(breadcrumb);
}

// Re-export Sentry for advanced usage (Error Boundary, etc.)
export { Sentry };
