import * as Sentry from "@sentry/svelte"

let initialized = false

export const init = (
    dsn: string | undefined,
    _tracingOrigins: (string | RegExp)[] = [],
    environment?: string,
    release?: string
) => {
    if (!dsn || typeof window === "undefined" || initialized) {
        return
    }

    Sentry.init({
        dsn,
        tunnel: "/_s",
        environment,
        release,
        integrations: [
            Sentry.browserTracingIntegration(),
            Sentry.replayIntegration({
                maskAllText: false,
                maskAllInputs: false,
                blockAllMedia: false,
            }),
        ],
        tracesSampleRate: 1.0,
        replaysSessionSampleRate: 1.0,
        replaysOnErrorSampleRate: 1.0,
    })

    initialized = true
}

export const currentTransaction = () => {
    try {
        const hub = (Sentry as any).getCurrentHub?.()
        return hub?.getScope?.()?.getTransaction?.() ?? null
    } catch {
        return null
    }
}

export const setUser = (user: Sentry.User) => {
    if (!initialized || typeof window === "undefined") {
        return
    }

    Sentry.setUser({ ...user, ip_address: "{{auto}}" })
}
