"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "SearchBundleResponse", {
    enumerable: true,
    get: function() {
        return SearchBundleResponse;
    }
});
const _constants = require("@tamanu/constants");
const _fhirTypes = require("@tamanu/shared/services/fhirTypes");
const _fhir = require("@tamanu/shared/utils/fhir");
const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
const _utils = require("../../utils");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let SearchBundleResponse = class SearchBundleResponse {
    addSelfUrl(req) {
        const baseUrl = (0, _utils.getBaseUrl)(req);
        this.options.selfurl = (0, _utils.getHL7Link)(baseUrl, req.query);
    }
    addIncluded(included) {
        this.included = this.included.concat(included);
    }
    addIssues(issues) {
        this.issues = this.issues.concat(issues);
    }
    get includes() {
        return new Set(this.included.map((r)=>r.fhirName));
    }
    asFhir() {
        const bundleData = {
            resourceType: 'Bundle',
            id: _crypto.default.randomUUID(),
            type: _constants.FHIR_BUNDLE_TYPES.SEARCHSET,
            timestamp: (0, _fhir.formatFhirDate)(new Date())
        };
        if (typeof this.options.total === 'number') {
            bundleData.total = this.options.total;
        }
        if (this.options.link) {
            bundleData.link = this.options.link;
        }
        if (this.options.selfurl) {
            var _bundleData;
            (_bundleData = bundleData).link || (_bundleData.link = []);
            bundleData.link.push({
                relation: 'self',
                url: this.options.selfurl
            });
        }
        bundleData.entry = this.resources.map((r)=>resourceToEntry(r, 'match')).concat(this.included.map((r)=>resourceToEntry(r, 'include')));
        if (this.issues.length > 0) {
            const oo = new _fhir.OperationOutcome(this.issues);
            oo.downgradeErrorsToWarnings();
            bundleData.issues = oo.asFhir();
        }
        return new _fhirTypes.FhirSearchSetBundle(bundleData);
    }
    constructor(resources, options = {}){
        _define_property(this, "included", []);
        _define_property(this, "issues", []);
        this.resources = resources;
        this.options = options;
    }
};
function resourceToEntry(resource, searchMode) {
    const entry = {
        resource: resource.asFhir()
    };
    entry.search = {
        mode: searchMode
    };
    return entry;
}

//# sourceMappingURL=SearchBundleResponse.js.map