import { SdkBase, E_RESPONSE_STATUS, E_RESPONSE_NO_VALUE, E_INVALID_JSON, E_RESPONSE_UNKNOWN, } from './SdkBase.js';
import { RouteBuilder } from './RouteBuilder.js';
import { SdkError } from './Errors.js';
export class OrganizationsSdk extends SdkBase {
    /**
     * Lists all user organizations.
     */
    async list(request = {}) {
        const { token } = request;
        const url = this.sdk.getUrl(RouteBuilder.organizations());
        const result = await this.sdk.http.get(url.toString(), { token });
        this.inspectCommonStatusCodes(result);
        const E_PREFIX = 'Unable to list your organizations. ';
        if (result.status !== 200) {
            this.logInvalidResponse(result);
            let e = this.createGenericSdkError(result.body);
            if (!e) {
                e = new SdkError(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`, result.status);
                e.response = result.body;
            }
            throw e;
        }
        if (!result.body) {
            throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
        }
        let data;
        try {
            data = JSON.parse(result.body);
        }
        catch {
            throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
        }
        if (!Array.isArray(data.items)) {
            throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
        }
        return data;
    }
    async create(orgName, request = {}) {
        const { token } = request;
        const url = this.sdk.getUrl(RouteBuilder.organizations());
        const body = {
            name: orgName,
        };
        const result = await this.sdk.http.post(url.toString(), {
            body: JSON.stringify(body),
            token,
            headers: {
                'Content-Type': 'application/json',
            },
        });
        this.inspectCommonStatusCodes(result);
        const E_PREFIX = 'Unable to create an organization. ';
        if (result.status !== 200) {
            throw new Error(`${E_PREFIX}Invalid response status: ${result.status}`);
        }
        if (!result.body) {
            throw new Error(`${E_PREFIX}Response has no value.`);
        }
        let data;
        try {
            data = JSON.parse(result.body);
        }
        catch {
            throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
        }
        if (!data.kind) {
            throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
        }
        return data;
    }
}
//# sourceMappingURL=OrganizationsSdk.js.map