import * as uuid from 'uuid';
import tracer from 'dd-trace';
import { NangoError } from './error.js';
import { errorToObject, getLogger } from '@nangohq/utils';
const logger = getLogger('ErrorManager');
export var ErrorSourceEnum;
(function (ErrorSourceEnum) {
    ErrorSourceEnum["PLATFORM"] = "platform";
    ErrorSourceEnum["CUSTOMER"] = "customer";
})(ErrorSourceEnum || (ErrorSourceEnum = {}));
class ErrorManager {
    /**
     * TODO: reuse information in res.locals when possible
     */
    report(err, config = { source: ErrorSourceEnum.PLATFORM }) {
        logger.error('Exception caught', errorToObject(err));
        if (err instanceof Error) {
            // Log to datadog manually
            // https://github.com/DataDog/dd-trace-js/issues/1944
            const span = tracer.scope().active();
            if (span) {
                span.addTags(config);
                span.setTag('error', err);
            }
        }
    }
    errResFromNangoErr(res, err) {
        if (err) {
            logger.error(`Response error`, errorToObject(err));
            if (!err.message) {
                res.status(err.status || 500).send({ error: { code: err.type || 'unknown_error', payload: err.payload } });
            }
            else {
                res.status(err.status || 500).send({ error: { message: err.message, code: err.type, payload: err.payload } });
            }
        }
        else {
            res.status(500).json({ error: { code: 'unknown_empty_error' } });
        }
    }
    errRes(res, type) {
        const err = new NangoError(type);
        this.errResFromNangoErr(res, err);
    }
    handleGenericError(err, _, res) {
        const errorId = uuid.v4();
        this.report(err);
        const supportError = new NangoError('generic_error_support', errorId);
        this.errResFromNangoErr(res, supportError);
    }
}
export default new ErrorManager();
//# sourceMappingURL=error.manager.js.map