"use client";

import {
    init as sentryInit,
    setUser as sentrySetUser,
    setTags as sentrySetTags,
    browserTracingIntegration,
    replayIntegration,
} from "@sentry/browser";

import { getAuthValue } from "./services/auth.service";
import { AUTH_USER_ID } from "@/constants/auth.constant";
import { APP_VERSION } from "@/constants/version.constant";
import type { AppInfo } from "./platform/app-info";

let SENTRY_INITIALIZED = false;

export function initSentry() {
    if (typeof window === "undefined") return;
    if (SENTRY_INITIALIZED) return;

    sentryInit({
        dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
        release: APP_VERSION,
        environment: process.env.NODE_ENV,

        tracesSampleRate: 0.5,

        replaysSessionSampleRate: 0.1,
        replaysOnErrorSampleRate: 1.0,

        integrations: [
            browserTracingIntegration(),
            replayIntegration(),
        ],
    });

    SENTRY_INITIALIZED = true;

    const userId = getAuthValue(AUTH_USER_ID);
    if (userId) {
        setSentryUser(userId);
    }
}

/** Which shell an event came from, so app-only bugs can be found. */
export function setSentryAppContext(info: AppInfo) {
    try {
        sentrySetTags({
            "app.platform": info.platform,
            "app.channel": info.channel,
            "app.native_version": info.native?.version ?? "none",
            "app.native_build": info.native ? String(info.native.build) : "none",
        });
    } catch { }
}

export function setSentryUser(userId: string | null) {
    try {
        if (!userId) {
            sentrySetUser(null);
            return;
        }

        sentrySetUser({
            id: userId,
        });
    } catch (err: any) { }
}