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

// Paste the @sentry/browser DSN for the jaak-for-woocommerce project here
// before testing. With the placeholder string the SDK will log a warning to
// the console and silently drop events.
const SENTRY_DSN = 'https://bd3b645ba0f80fff939178d86353467c@o4507568947200000.ingest.de.sentry.io/4511292185641040';

const jaak_version = typeof window.JAAK_VERSION === 'string' && window.JAAK_VERSION.length > 0
	? window.JAAK_VERSION
	: null;

Sentry.init({
	dsn: SENTRY_DSN,
	environment: window.JAAK_SENTRY_ENV,
	release: jaak_version === null ? undefined : `jaak-for-woocommerce@${jaak_version}`,
	// We only use Sentry for manual `captureEvent` calls in this plugin;
	// performance/profiling features are off.
	tracesSampleRate: 0,
	sendDefaultPii: true,
	// Default is 3, which collapses `billing`, `shipping`, `meta_data` etc. to
	// `"[Object]"` / `"[Array]"` placeholders. We need full visibility into
	// nested order data to design merchant-specific address parsers.
	normalizeDepth: 10,
	normalizeMaxBreadth: 5000,
	initialScope: {
		// `user` is omitted when there's no WP user (e.g. logged-out edge case)
		// because exactOptionalPropertyTypes disallows passing `undefined`.
		...(window.JAAK_WP_USER ? { user: window.JAAK_WP_USER } : {}),
		tags: {
			wp_site_url: window.WORDPRESS_SITE_URL,
			wp_site_url_hostname: get_hostname_from_url(window.WORDPRESS_SITE_URL),
			jaak_version,
			wp_version: typeof window.JAAK_WP_VERSION === 'string' ? window.JAAK_WP_VERSION : null,
			wc_version: typeof window.JAAK_WC_VERSION === 'string' ? window.JAAK_WC_VERSION : null,
			php_version: typeof window.JAAK_PHP_VERSION === 'string' ? window.JAAK_PHP_VERSION : null,
		},
	},
});

function get_hostname_from_url(url: string | undefined): string | null {
	if (typeof url !== 'string' || url.length === 0) {
		return null;
	}
	try {
		return new URL(url).hostname;
	}
	catch {
		return null;
	}
}
