import { NAMESPACES } from "./endpoints.js";
import { HttpClient } from "./http.js";
import { EntityObjectsService } from "./objects.js";
import { createMetadataService } from "./metadata/service.js";
import { createNamespaceService, } from "./service.js";
export class Clarizen {
    http;
    authentication;
    applications;
    bulk;
    data;
    files;
    metadata;
    utils;
    objects;
    constructor(baseUrlOrOptions, apiToken) {
        const options = typeof baseUrlOrOptions === "string"
            ? { baseUrl: baseUrlOrOptions, apiToken }
            : baseUrlOrOptions;
        const baseUrl = (options.baseUrl ?? "https://api.clarizen.com").replace(/\/$/, "");
        let auth;
        if (options.sessionId) {
            auth = { type: "session", sessionId: options.sessionId };
        }
        else if (options.apiToken) {
            auth = { type: "apiKey", token: options.apiToken };
        }
        else {
            auth = { type: "none" };
        }
        this.http = new HttpClient(baseUrl, auth);
        const authBase = createNamespaceService(this.http, "authentication");
        this.authentication = {
            getServerDefinition: (body) => authBase.getServerDefinition(body),
            getSessionInfo: () => authBase.getSessionInfo(),
            logout: authBase.logout,
            login: async (params) => {
                const result = (await authBase.login(params));
                this.useSession(result.sessionId);
                return result;
            },
        };
        this.applications = createNamespaceService(this.http, "applications");
        this.bulk = createNamespaceService(this.http, "bulk");
        this.files = createNamespaceService(this.http, "files");
        this.metadata = createMetadataService(this.http);
        this.utils = createNamespaceService(this.http, "utils");
        this.objects = new EntityObjectsService(this.http);
        this.data = createNamespaceService(this.http, "data");
    }
    get baseUrl() {
        return this.http.getBaseUrl();
    }
    async loginWithDiscovery(params) {
        const definition = await this.authentication.getServerDefinition(params);
        this.http.setBaseUrl(definition.serverLocation);
        return this.authentication.login(params);
    }
    useSession(sessionId) {
        this.http.setAuth({ type: "session", sessionId });
    }
    useApiKey(apiToken) {
        this.http.setAuth({ type: "apiKey", token: apiToken });
    }
    get sessionId() {
        const auth = this.http.getAuth();
        return auth.type === "session" ? auth.sessionId : undefined;
    }
    call(namespace, operation, body, query) {
        const service = this[namespace];
        return service(operation, body, query);
    }
    static createForLogin(baseUrl = "https://api.clarizen.com") {
        return new Clarizen({ baseUrl });
    }
    static namespaces = NAMESPACES;
}
//# sourceMappingURL=clarizen.js.map