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

type AppSurface = 'guest' | 'admin' | 'inertia';

const defaultTracesSampleRate = 0.05;

const parseSampleRate = (value: string | undefined): number => {
    const parsed = Number.parseFloat(value ?? '');

    if (Number.isNaN(parsed) || parsed < 0) {
        return defaultTracesSampleRate;
    }

    return parsed;
};

export const initSentry = (app: AppSurface): void => {
    const dsn = import.meta.env.VITE_SENTRY_DSN;

    if (! dsn) {
        return;
    }

    Sentry.init({
        dsn,
        environment: import.meta.env.VITE_SENTRY_ENV ?? import.meta.env.MODE,
        release: import.meta.env.VITE_SENTRY_RELEASE,
        tracesSampleRate: parseSampleRate(import.meta.env.VITE_SENTRY_TRACES_SAMPLE_RATE),
        beforeSend(event) {
            event.tags = {
                ...event.tags,
                app,
            };

            return event;
        },
        normalizeDepth: 6,
    });
};

export { Sentry };
