/**
 * Sentry/GlitchTip initialization for frontend error tracking.
 *
 * @see Story 1.8 - T8: Frontend Monitoring (AC: #1)
 */

import * as Sentry from '@sentry/sveltekit';

/**
 * Initialize Sentry for error tracking.
 *
 * Call this once in +hooks.client.ts or +layout.svelte.
 * Critical: No PII is sent to GlitchTip (RGPD compliance).
 */
export function initSentry(options: {
	dsn: string;
	environment: string;
	userId?: string;
	tenantId?: string;
}): void {
	if (!options.dsn) {
		console.warn('[Sentry] DSN not configured, error tracking disabled');
		return;
	}

	Sentry.init({
		dsn: options.dsn,
		environment: options.environment,

		// Capture 100% of errors
		sampleRate: 1.0,

		// Disable performance tracing (using server-side Prometheus)
		tracesSampleRate: 0.0,

		// CRITICAL: No PII in error reports (RGPD compliance)
		sendDefaultPii: false,

		// Scrub sensitive data before sending
		beforeSend(event) {
			// Remove any accidentally captured PII
			if (event.request?.headers) {
				delete event.request.headers['Authorization'];
				delete event.request.headers['Cookie'];
			}

			// Remove email-like strings from breadcrumbs
			if (event.breadcrumbs) {
				event.breadcrumbs = event.breadcrumbs.map((breadcrumb) => {
					if (breadcrumb.message && breadcrumb.message.includes('@')) {
						breadcrumb.message = '[EMAIL_REDACTED]';
					}
					return breadcrumb;
				});
			}

			return event;
		},

		// Ignore common non-errors
		ignoreErrors: [
			// Browser extensions
			'ResizeObserver loop',
			'ResizeObserver loop limit exceeded',
			// Network errors (expected in offline scenarios)
			'NetworkError',
			'Failed to fetch',
			'Load failed',
			// User cancellation
			'AbortError',
		]
	});

	// Set user context (ID only, no PII)
	if (options.userId) {
		Sentry.setUser({ id: options.userId });
	}

	// Set tenant context as tag
	if (options.tenantId) {
		Sentry.setTag('tenant_id', options.tenantId);
	}
}

/**
 * Update user context after login.
 *
 * Only sends user ID, never email or name (RGPD compliance).
 */
export function setUserContext(userId: string, tenantId?: string): void {
	Sentry.setUser({ id: userId });

	if (tenantId) {
		Sentry.setTag('tenant_id', tenantId);
	}
}

/**
 * Clear user context on logout.
 */
export function clearUserContext(): void {
	Sentry.setUser(null);
}

/**
 * Capture an error manually.
 *
 * Use this for caught exceptions that should still be tracked.
 */
export function captureError(error: unknown, context?: Record<string, unknown>): void {
	Sentry.captureException(error, context ? { extra: context } : undefined);
}

/**
 * Add a breadcrumb for debugging.
 *
 * Breadcrumbs show the trail of actions leading to an error.
 */
export function addBreadcrumb(
	category: string,
	message: string,
	data?: Record<string, unknown>
): void {
	Sentry.addBreadcrumb({
		category,
		message,
		level: 'info',
		...(data && { data })
	});
}
