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

const isSentryAvailable = typeof __SENTRY_DSN !== 'undefined' && typeof __SENTRY_RELEASE !== 'undefined';

type InitReturn = ReturnType<typeof Sentry.init>;

/** Bootstraps Sentry only when DSN and release information are provided. */
export function initSentry(): InitReturn | undefined
{
    if (!isSentryAvailable)
    {
        return undefined;
    }

    const globalOptions = (window as typeof window & { __OPTIONS__?: typeof __OPTIONS__ & { environment?: string } }).__OPTIONS__;
    const environment = globalOptions?.environment ?? globalOptions?.env ?? __OPTIONS__?.env;

    const sentry = Sentry.init({
        environment,
        dsn: __SENTRY_DSN,
        release: __SENTRY_RELEASE,
        attachStacktrace: true,
        ignoreErrors: [],
    });

    const userId = (window as typeof window & { user_id?: string }).user_id;

    if (userId)
    {
        Sentry.setUser({ id: userId });
    }

    return sentry;
}
