import { getMonitoringConfig } from './config';

let initialized = false;

export function initSentry() {
  if (initialized) return;

  const config = getMonitoringConfig();

  if (!config.SENTRY_DSN) {
    console.log('[Sentry] DSN not configured, error tracking disabled');
    return;
  }

  try {
    const Sentry = require('@sentry/node');

    Sentry.init({
      dsn: config.SENTRY_DSN,
      environment: config.SENTRY_ENVIRONMENT,
      release: config.SENTRY_RELEASE,
      tracesSampleRate: config.SENTRY_TRACES_SAMPLE_RATE,
      attachStacktrace: true,
      debug: config.SENTRY_ENVIRONMENT === 'development',
      beforeSend(event: any) {
        const req = (event as any).request;
        if (req?.url) {
          try {
            const url = new URL(req.url);
            req.url = url.origin + url.pathname;
          } catch {
            // fallback: keep original URL
          }
        }
        return event;
      },
    });

    initialized = true;
    console.log(`[Sentry] Error tracking initialized for "${config.SENTRY_ENVIRONMENT}"`);
  } catch (err) {
    console.warn('[Sentry] Initialization skipped:', (err as Error).message);
  }
}

export function captureSentryError(error: Error | string, context?: Record<string, unknown>) {
  try {
    const Sentry = require('@sentry/node');
    const err = typeof error === 'string' ? new Error(error) : error;
    Sentry.captureException(err, { tags: context as Record<string, string> | undefined });
  } catch {
    console.warn('[Sentry] Error capture skipped (not initialized):', error);
  }
}

export function captureSentryMessage(message: string, level: 'info' | 'warning' | 'error' = 'info') {
  try {
    const Sentry = require('@sentry/node');
    Sentry.captureMessage(message, { level });
  } catch {
    console.warn('[Sentry] Message capture skipped (not initialized)');
  }
}

export function setSentryUser(userId: string, metadata?: Record<string, string>) {
  try {
    const Sentry = require('@sentry/node');
    Sentry.setUser({ id: userId, ...metadata });
  } catch {
    // silently ignore
  }
}

export function setSentryContext(name: string, data: Record<string, unknown>) {
  try {
    const Sentry = require('@sentry/node');
    Sentry.setContext(name, data);
  } catch {
    // silently ignore
  }
}

export function getSentryHub() {
  try {
    const Sentry = require('@sentry/node');
    return Sentry.getCurrentScope?.() || Sentry.getCurrentHub?.() || Sentry.hub;
  } catch {
    return null;
  }
}
