import * as Sentry from '@sentry/sveltekit';
import { env } from '$env/dynamic/public';
import { initializeFaro, getWebInstrumentations } from '@grafana/faro-web-sdk';

// Sentry / GlitchTip client-side error tracking.
// No-op when PUBLIC_GLITCHTIP_DSN is unset (e.g. local dev).
if (env.PUBLIC_GLITCHTIP_DSN) {
	Sentry.init({
		dsn: env.PUBLIC_GLITCHTIP_DSN,
		tracesSampleRate: 0.1,
		// Must match the release name used when uploading source maps in CI
		// (BUILD_VERSION injected by Dockerfile as PUBLIC_BUILD_VERSION).
		release: env.PUBLIC_BUILD_VERSION || undefined
	});
}

// Grafana Faro RUM — browser performance monitoring (Web Vitals, traces, errors).
// No-op when PUBLIC_FARO_COLLECTOR_URL is unset (e.g. local dev).
if (env.PUBLIC_FARO_COLLECTOR_URL) {
	initializeFaro({
		url: env.PUBLIC_FARO_COLLECTOR_URL,
		app: {
			name: 'libnovel-ui',
			version: env.PUBLIC_BUILD_VERSION || 'dev',
			environment: 'production'
		},
		instrumentations: [
			// Core Web Vitals (LCP, CLS, INP, TTFB, FCP) + JS errors + console
			...getWebInstrumentations({ captureConsole: false })
		]
	});
}

export const handleError = Sentry.handleErrorWithSentry();
