"use strict";

// Local crash-event symbolication dispatcher.
//
// The reporter-specific modules are still the source of truth for each event
// shape. This wrapper lets the CLI and custom scripts feed captured JSON events
// through the same transforms without wiring a browser SDK hook first.

const { createSentryEventProcessor } = require("./sentry.js");
const { createBugsnagOnError } = require("./bugsnag.js");
const { createRollbarTransform } = require("./rollbar.js");
const { createDatadogBeforeSend } = require("./datadog.js");
const { createHoneybadgerBeforeNotify } = require("./honeybadger.js");
const { createRaygunBeforeSend } = require("./raygun.js");
const { createAirbrakeFilter } = require("./airbrake.js");
const { createAppSignalDecorator } = require("./appsignal.js");

const SUPPORTED_EVENT_REPORTERS = [
    "sentry",
    "bugsnag",
    "rollbar",
    "datadog",
    "honeybadger",
    "raygun",
    "airbrake",
    "appsignal",
];

function normalizeReporterName(name) {
    return String(name || "").trim().toLowerCase();
}

function symbolicateEvent(reporter, event, lookup, options) {
    const kind = normalizeReporterName(reporter);
    if (!SUPPORTED_EVENT_REPORTERS.includes(kind)) {
        throw new Error("unsupported event reporter: " + reporter);
    }
    if (!event || typeof event !== "object" || Array.isArray(event)) {
        throw new Error("event JSON must be an object");
    }
    const opts = options || {};
    switch (kind) {
    case "sentry":
        return createSentryEventProcessor(lookup, {
            preserveOriginal: !!opts.preserveOriginal,
        })(event);
    case "bugsnag":
        createBugsnagOnError(lookup)(event);
        return event;
    case "rollbar":
        createRollbarTransform(lookup)(event, {}, function () { /* CLI no-op */ });
        return event;
    case "datadog":
        createDatadogBeforeSend(lookup)(event, {});
        return event;
    case "honeybadger":
        createHoneybadgerBeforeNotify(lookup)(event);
        return event;
    case "raygun":
        return createRaygunBeforeSend(lookup)(event);
    case "airbrake":
        return createAirbrakeFilter(lookup)(event);
    case "appsignal":
        return createAppSignalDecorator(lookup)(event);
    default:
        throw new Error("unsupported event reporter: " + reporter);
    }
}

module.exports = {
    SUPPORTED_EVENT_REPORTERS,
    normalizeReporterName,
    symbolicateEvent,
};
