"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "OperationOutcome", {
    enumerable: true,
    get: function() {
        return OperationOutcome;
    }
});
const _lodash = require("lodash");
const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
const _constants = require("@tamanu/constants");
const _errors = require("./errors");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let OperationOutcome = class OperationOutcome extends Error {
    constructor(errors){
        super('OperationOutcome: one or more errors (THIS SHOULD NEVER BE SEEN)');
        this.errors = errors.flatMap((err)=>{
            if (err instanceof OperationOutcome) {
                return err.errors;
            }
            if (err instanceof _errors.FhirError) {
                return [
                    err
                ];
            }
            return [
                new _errors.FhirError(err.toString(), {
                    diagnostics: err.stack
                })
            ];
        });
    }
    status() {
        const codes = this.errors.map((err)=>err.status);
        codes.sort();
        return (0, _lodash.last)(codes);
    }
    asFhir() {
        return {
            resourceType: 'OperationOutcome',
            id: _crypto.default.randomUUID(),
            issue: this.errors.map((err)=>err.asFhir())
        };
    }
    /**
   * Downgrade all errors to warning severity, leave informationals alone.
   *
   * This is useful (and required!) when returning issues alongside a successful
   * response.
   */ downgradeErrorsToWarnings() {
        this.errors.forEach((err)=>{
            if (!(err instanceof _errors.FhirError)) return;
            if (err.severity !== _constants.FHIR_ISSUE_SEVERITY.INFORMATION) {
                // eslint-disable-next-line no-param-reassign
                err.severity = _constants.FHIR_ISSUE_SEVERITY.WARNING;
            }
        });
    }
    static fromYupError(validationError /*: ValidationError */ , pathPrefix = undefined) {
        const errors = [];
        if (validationError.inner.length > 0) {
            for (const error of validationError.inner){
                errors.push(new _errors.Invalid(error.message, {
                    expression: [
                        pathPrefix,
                        error.path
                    ].filter((x)=>x).join('.') || undefined
                }));
            }
        } else {
            errors.push(new _errors.Invalid(validationError.message, {
                expression: pathPrefix
            }));
        }
        return new this(errors);
    }
};

//# sourceMappingURL=OperationOutcome.js.map