"use strict";
/**
 * This file was auto-generated by Fern from our API Definition.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Attachments = void 0;
const environments = __importStar(require("../../../../../../environments"));
const core = __importStar(require("../../../../../../core"));
const headers_1 = require("../../../../../../core/headers");
const serializers = __importStar(require("../../../../../../serialization/index"));
const errors = __importStar(require("../../../../../../errors/index"));
class Attachments {
    constructor(_options) {
        this._options = _options;
    }
    /**
     * Returns a list of `Attachment` objects.
     *
     * @param {Merge.ticketing.AttachmentsListRequest} request
     * @param {Attachments.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.ticketing.attachments.list()
     */
    list(request = {}, requestOptions) {
        return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions));
    }
    __list() {
        return __awaiter(this, arguments, void 0, function* (request = {}, requestOptions) {
            var _a, _b, _c, _d;
            const { createdAfter, createdBefore, cursor, expand, includeDeletedData, includeRemoteData, includeShellData, modifiedAfter, modifiedBefore, pageSize, remoteCreatedAfter, remoteId, ticketId, } = request;
            const _queryParams = {};
            if (createdAfter != null) {
                _queryParams["created_after"] = createdAfter.toISOString();
            }
            if (createdBefore != null) {
                _queryParams["created_before"] = createdBefore.toISOString();
            }
            if (cursor != null) {
                _queryParams["cursor"] = cursor;
            }
            if (expand != null) {
                _queryParams["expand"] = expand;
            }
            if (includeDeletedData != null) {
                _queryParams["include_deleted_data"] = includeDeletedData.toString();
            }
            if (includeRemoteData != null) {
                _queryParams["include_remote_data"] = includeRemoteData.toString();
            }
            if (includeShellData != null) {
                _queryParams["include_shell_data"] = includeShellData.toString();
            }
            if (modifiedAfter != null) {
                _queryParams["modified_after"] = modifiedAfter.toISOString();
            }
            if (modifiedBefore != null) {
                _queryParams["modified_before"] = modifiedBefore.toISOString();
            }
            if (pageSize != null) {
                _queryParams["page_size"] = pageSize.toString();
            }
            if (remoteCreatedAfter != null) {
                _queryParams["remote_created_after"] = remoteCreatedAfter.toISOString();
            }
            if (remoteId != null) {
                _queryParams["remote_id"] = remoteId;
            }
            if (ticketId != null) {
                _queryParams["ticket_id"] = ticketId;
            }
            const _response = yield ((_a = this._options.fetcher) !== null && _a !== void 0 ? _a : core.fetcher)({
                url: core.url.join((_c = (_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.MergeEnvironment.Production, "ticketing/v1/attachments"),
                method: "GET",
                headers: (0, headers_1.mergeHeaders)((_d = this._options) === null || _d === void 0 ? void 0 : _d.headers, (0, headers_1.mergeOnlyDefinedHeaders)({
                    Authorization: yield this._getAuthorizationHeader(),
                    "X-Account-Token": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.accountToken,
                }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
                queryParameters: Object.assign(Object.assign({}, _queryParams), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.queryParams),
                timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
                maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
                abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
            });
            if (_response.ok) {
                return {
                    data: serializers.ticketing.PaginatedAttachmentList.parseOrThrow(_response.body, {
                        unrecognizedObjectKeys: "passthrough",
                        allowUnrecognizedUnionMembers: true,
                        allowUnrecognizedEnumValues: true,
                        skipValidation: true,
                        breadcrumbsPrefix: ["response"],
                    }),
                    rawResponse: _response.rawResponse,
                };
            }
            if (_response.error.reason === "status-code") {
                throw new errors.MergeError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.body,
                    rawResponse: _response.rawResponse,
                });
            }
            switch (_response.error.reason) {
                case "non-json":
                    throw new errors.MergeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.rawBody,
                        rawResponse: _response.rawResponse,
                    });
                case "timeout":
                    throw new errors.MergeTimeoutError("Timeout exceeded when calling GET /ticketing/v1/attachments.");
                case "unknown":
                    throw new errors.MergeError({
                        message: _response.error.errorMessage,
                        rawResponse: _response.rawResponse,
                    });
            }
        });
    }
    /**
     * Creates an `Attachment` object with the given values.
     *
     * @param {Merge.ticketing.TicketingAttachmentEndpointRequest} request
     * @param {Attachments.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.ticketing.attachments.create({
     *         model: {}
     *     })
     */
    create(request, requestOptions) {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }
    __create(request, requestOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d;
            const { isDebugMode, runAsync } = request, _body = __rest(request, ["isDebugMode", "runAsync"]);
            const _queryParams = {};
            if (isDebugMode != null) {
                _queryParams["is_debug_mode"] = isDebugMode.toString();
            }
            if (runAsync != null) {
                _queryParams["run_async"] = runAsync.toString();
            }
            const _response = yield ((_a = this._options.fetcher) !== null && _a !== void 0 ? _a : core.fetcher)({
                url: core.url.join((_c = (_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.MergeEnvironment.Production, "ticketing/v1/attachments"),
                method: "POST",
                headers: (0, headers_1.mergeHeaders)((_d = this._options) === null || _d === void 0 ? void 0 : _d.headers, (0, headers_1.mergeOnlyDefinedHeaders)({
                    Authorization: yield this._getAuthorizationHeader(),
                    "X-Account-Token": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.accountToken,
                }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
                contentType: "application/json",
                queryParameters: Object.assign(Object.assign({}, _queryParams), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.queryParams),
                requestType: "json",
                body: serializers.ticketing.TicketingAttachmentEndpointRequest.jsonOrThrow(_body, {
                    unrecognizedObjectKeys: "strip",
                }),
                timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
                maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
                abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
            });
            if (_response.ok) {
                return {
                    data: serializers.ticketing.TicketingAttachmentResponse.parseOrThrow(_response.body, {
                        unrecognizedObjectKeys: "passthrough",
                        allowUnrecognizedUnionMembers: true,
                        allowUnrecognizedEnumValues: true,
                        skipValidation: true,
                        breadcrumbsPrefix: ["response"],
                    }),
                    rawResponse: _response.rawResponse,
                };
            }
            if (_response.error.reason === "status-code") {
                throw new errors.MergeError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.body,
                    rawResponse: _response.rawResponse,
                });
            }
            switch (_response.error.reason) {
                case "non-json":
                    throw new errors.MergeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.rawBody,
                        rawResponse: _response.rawResponse,
                    });
                case "timeout":
                    throw new errors.MergeTimeoutError("Timeout exceeded when calling POST /ticketing/v1/attachments.");
                case "unknown":
                    throw new errors.MergeError({
                        message: _response.error.errorMessage,
                        rawResponse: _response.rawResponse,
                    });
            }
        });
    }
    /**
     * Returns an `Attachment` object with the given `id`.
     *
     * @param {string} id
     * @param {Merge.ticketing.AttachmentsRetrieveRequest} request
     * @param {Attachments.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.ticketing.attachments.retrieve("id")
     */
    retrieve(id, request = {}, requestOptions) {
        return core.HttpResponsePromise.fromPromise(this.__retrieve(id, request, requestOptions));
    }
    __retrieve(id_1) {
        return __awaiter(this, arguments, void 0, function* (id, request = {}, requestOptions) {
            var _a, _b, _c, _d;
            const { expand, includeRemoteData, includeShellData } = request;
            const _queryParams = {};
            if (expand != null) {
                _queryParams["expand"] = expand;
            }
            if (includeRemoteData != null) {
                _queryParams["include_remote_data"] = includeRemoteData.toString();
            }
            if (includeShellData != null) {
                _queryParams["include_shell_data"] = includeShellData.toString();
            }
            const _response = yield ((_a = this._options.fetcher) !== null && _a !== void 0 ? _a : core.fetcher)({
                url: core.url.join((_c = (_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.MergeEnvironment.Production, `ticketing/v1/attachments/${encodeURIComponent(id)}`),
                method: "GET",
                headers: (0, headers_1.mergeHeaders)((_d = this._options) === null || _d === void 0 ? void 0 : _d.headers, (0, headers_1.mergeOnlyDefinedHeaders)({
                    Authorization: yield this._getAuthorizationHeader(),
                    "X-Account-Token": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.accountToken,
                }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
                queryParameters: Object.assign(Object.assign({}, _queryParams), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.queryParams),
                timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
                maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
                abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
            });
            if (_response.ok) {
                return {
                    data: serializers.ticketing.Attachment.parseOrThrow(_response.body, {
                        unrecognizedObjectKeys: "passthrough",
                        allowUnrecognizedUnionMembers: true,
                        allowUnrecognizedEnumValues: true,
                        skipValidation: true,
                        breadcrumbsPrefix: ["response"],
                    }),
                    rawResponse: _response.rawResponse,
                };
            }
            if (_response.error.reason === "status-code") {
                throw new errors.MergeError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.body,
                    rawResponse: _response.rawResponse,
                });
            }
            switch (_response.error.reason) {
                case "non-json":
                    throw new errors.MergeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.rawBody,
                        rawResponse: _response.rawResponse,
                    });
                case "timeout":
                    throw new errors.MergeTimeoutError("Timeout exceeded when calling GET /ticketing/v1/attachments/{id}.");
                case "unknown":
                    throw new errors.MergeError({
                        message: _response.error.errorMessage,
                        rawResponse: _response.rawResponse,
                    });
            }
        });
    }
    /**
     * Returns the `File` content with the given `id` as a stream of bytes.
     */
    downloadRetrieve(id, request = {}, requestOptions) {
        return core.HttpResponsePromise.fromPromise(this.__downloadRetrieve(id, request, requestOptions));
    }
    __downloadRetrieve(id_1) {
        return __awaiter(this, arguments, void 0, function* (id, request = {}, requestOptions) {
            var _a, _b, _c, _d;
            const { includeShellData, mimeType } = request;
            const _queryParams = {};
            if (includeShellData != null) {
                _queryParams["include_shell_data"] = includeShellData.toString();
            }
            if (mimeType != null) {
                _queryParams["mime_type"] = mimeType;
            }
            const _response = yield ((_a = this._options.fetcher) !== null && _a !== void 0 ? _a : core.fetcher)({
                url: core.url.join((_c = (_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.MergeEnvironment.Production, `ticketing/v1/attachments/${encodeURIComponent(id)}/download`),
                method: "GET",
                headers: (0, headers_1.mergeHeaders)((_d = this._options) === null || _d === void 0 ? void 0 : _d.headers, (0, headers_1.mergeOnlyDefinedHeaders)({
                    Authorization: yield this._getAuthorizationHeader(),
                    "X-Account-Token": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.accountToken,
                }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
                queryParameters: Object.assign(Object.assign({}, _queryParams), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.queryParams),
                responseType: "streaming",
                timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
                maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
                abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
            });
            if (_response.ok) {
                return { data: _response.body, rawResponse: _response.rawResponse };
            }
            if (_response.error.reason === "status-code") {
                throw new errors.MergeError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.body,
                    rawResponse: _response.rawResponse,
                });
            }
            switch (_response.error.reason) {
                case "non-json":
                    throw new errors.MergeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.rawBody,
                        rawResponse: _response.rawResponse,
                    });
                case "timeout":
                    throw new errors.MergeTimeoutError("Timeout exceeded when calling GET /ticketing/v1/attachments/{id}/download.");
                case "unknown":
                    throw new errors.MergeError({
                        message: _response.error.errorMessage,
                        rawResponse: _response.rawResponse,
                    });
            }
        });
    }
    /**
     * Returns metadata for `TicketingAttachment` POSTs.
     *
     * @param {Attachments.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.ticketing.attachments.metaPostRetrieve()
     */
    metaPostRetrieve(requestOptions) {
        return core.HttpResponsePromise.fromPromise(this.__metaPostRetrieve(requestOptions));
    }
    __metaPostRetrieve(requestOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d;
            const _response = yield ((_a = this._options.fetcher) !== null && _a !== void 0 ? _a : core.fetcher)({
                url: core.url.join((_c = (_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.MergeEnvironment.Production, "ticketing/v1/attachments/meta/post"),
                method: "GET",
                headers: (0, headers_1.mergeHeaders)((_d = this._options) === null || _d === void 0 ? void 0 : _d.headers, (0, headers_1.mergeOnlyDefinedHeaders)({
                    Authorization: yield this._getAuthorizationHeader(),
                    "X-Account-Token": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.accountToken,
                }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
                queryParameters: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.queryParams,
                timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
                maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
                abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
            });
            if (_response.ok) {
                return {
                    data: serializers.ticketing.MetaResponse.parseOrThrow(_response.body, {
                        unrecognizedObjectKeys: "passthrough",
                        allowUnrecognizedUnionMembers: true,
                        allowUnrecognizedEnumValues: true,
                        skipValidation: true,
                        breadcrumbsPrefix: ["response"],
                    }),
                    rawResponse: _response.rawResponse,
                };
            }
            if (_response.error.reason === "status-code") {
                throw new errors.MergeError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.body,
                    rawResponse: _response.rawResponse,
                });
            }
            switch (_response.error.reason) {
                case "non-json":
                    throw new errors.MergeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.rawBody,
                        rawResponse: _response.rawResponse,
                    });
                case "timeout":
                    throw new errors.MergeTimeoutError("Timeout exceeded when calling GET /ticketing/v1/attachments/meta/post.");
                case "unknown":
                    throw new errors.MergeError({
                        message: _response.error.errorMessage,
                        rawResponse: _response.rawResponse,
                    });
            }
        });
    }
    _getAuthorizationHeader() {
        return __awaiter(this, void 0, void 0, function* () {
            return `Bearer ${yield core.Supplier.get(this._options.apiKey)}`;
        });
    }
}
exports.Attachments = Attachments;
