"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ambiguous_1 = require("../../errors/ambiguous");
const not_found_1 = require("../../errors/not-found");
class AddonAttachmentResolver {
    constructor(heroku) {
        this.heroku = heroku;
        this.attachmentHeaders = {
            Accept: 'application/vnd.heroku+json; version=3.sdk',
            'Accept-Inclusion': 'addon:plan,config_vars',
        };
    }
    async resolve(appId, attachmentId, options = {}) {
        const { body: attachments } = await this.heroku.post('/actions/addon-attachments/resolve', {
            // eslint-disable-next-line camelcase
            body: { addon_attachment: attachmentId, addon_service: options.addonService, app: appId },
            headers: this.attachmentHeaders,
        });
        return this.singularize(attachments, options.namespace);
    }
    singularize(attachments, namespace) {
        let matches;
        if (namespace) {
            matches = attachments.filter(m => m.namespace === namespace);
        }
        else if (attachments.length > 1) {
            // In cases that aren't specific enough, keep only attachments without a namespace
            matches = attachments.filter(m => !Reflect.has(m, 'namespace') || m.namespace === null);
        }
        else {
            matches = attachments;
        }
        switch (matches.length) {
            case 0: {
                throw new not_found_1.NotFound();
            }
            case 1: {
                return matches[0];
            }
            default: {
                throw new ambiguous_1.AmbiguousError(matches, 'addon_attachment');
            }
        }
    }
}
exports.default = AddonAttachmentResolver;
