// This file was auto-generated by Fern from our API Definition.

import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js";
import { mergeHeaders } from "../../../../core/headers.js";
import * as core from "../../../../core/index.js";
import * as environments from "../../../../environments.js";
import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
import * as errors from "../../../../errors/index.js";
import * as LatitudeApi from "../../../index.js";

export declare namespace ApiKeysClient {
    export type Options = BaseClientOptions;

    export interface RequestOptions extends BaseRequestOptions {}
}

export class ApiKeysClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<ApiKeysClient.Options>;

    constructor(options: ApiKeysClient.Options = {}) {
        this._options = normalizeClientOptionsWithAuth(options);
    }

    /**
     * Returns all API keys for the organization. Tokens are not included in the list response.
     *
     * @param {ApiKeysClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.UnauthorizedError}
     *
     * @example
     *     await client.apiKeys.list()
     */
    public list(requestOptions?: ApiKeysClient.RequestOptions): core.HttpResponsePromise<LatitudeApi.ApiKeyList> {
        return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
    }

    private async __list(
        requestOptions?: ApiKeysClient.RequestOptions,
    ): Promise<core.WithRawResponse<LatitudeApi.ApiKeyList>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await core.fetcher({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.LatitudeApiEnvironment.Production,
                "v1/api-keys",
            ),
            method: "GET",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: _response.body as LatitudeApi.ApiKeyList, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new LatitudeApi.UnauthorizedError(
                        _response.error.body as LatitudeApi.Error_,
                        _response.rawResponse,
                    );
                default:
                    throw new errors.LatitudeApiError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/api-keys");
    }

    /**
     * Generates a new API key for the organization. The token is only returned once — store it securely.
     *
     * @param {LatitudeApi.CreateApiKeyBody} request
     * @param {ApiKeysClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.BadRequestError}
     * @throws {@link LatitudeApi.UnauthorizedError}
     * @throws {@link LatitudeApi.NotFoundError}
     *
     * @example
     *     await client.apiKeys.create({
     *         name: "name"
     *     })
     */
    public create(
        request: LatitudeApi.CreateApiKeyBody,
        requestOptions?: ApiKeysClient.RequestOptions,
    ): core.HttpResponsePromise<LatitudeApi.ApiKey> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: LatitudeApi.CreateApiKeyBody,
        requestOptions?: ApiKeysClient.RequestOptions,
    ): Promise<core.WithRawResponse<LatitudeApi.ApiKey>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await core.fetcher({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.LatitudeApiEnvironment.Production,
                "v1/api-keys",
            ),
            method: "POST",
            headers: _headers,
            contentType: "application/json",
            queryParameters: requestOptions?.queryParams,
            requestType: "json",
            body: request,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: _response.body as LatitudeApi.ApiKey, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 400:
                    throw new LatitudeApi.BadRequestError(
                        _response.error.body as LatitudeApi.Error_,
                        _response.rawResponse,
                    );
                case 401:
                    throw new LatitudeApi.UnauthorizedError(
                        _response.error.body as LatitudeApi.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new LatitudeApi.NotFoundError(
                        _response.error.body as LatitudeApi.Error_,
                        _response.rawResponse,
                    );
                default:
                    throw new errors.LatitudeApiError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/api-keys");
    }

    /**
     * Soft-deletes an API key, immediately invalidating it.
     *
     * @param {string} id - Resource ID
     * @param {ApiKeysClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.UnauthorizedError}
     * @throws {@link LatitudeApi.NotFoundError}
     *
     * @example
     *     await client.apiKeys.revoke("id")
     */
    public revoke(id: string, requestOptions?: ApiKeysClient.RequestOptions): core.HttpResponsePromise<void> {
        return core.HttpResponsePromise.fromPromise(this.__revoke(id, requestOptions));
    }

    private async __revoke(
        id: string,
        requestOptions?: ApiKeysClient.RequestOptions,
    ): Promise<core.WithRawResponse<void>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await core.fetcher({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.LatitudeApiEnvironment.Production,
                `v1/api-keys/${core.url.encodePathParam(id)}`,
            ),
            method: "DELETE",
            headers: _headers,
            queryParameters: requestOptions?.queryParams,
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return { data: undefined, rawResponse: _response.rawResponse };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new LatitudeApi.UnauthorizedError(
                        _response.error.body as LatitudeApi.Error_,
                        _response.rawResponse,
                    );
                case 404:
                    throw new LatitudeApi.NotFoundError(
                        _response.error.body as LatitudeApi.Error_,
                        _response.rawResponse,
                    );
                default:
                    throw new errors.LatitudeApiError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/v1/api-keys/{id}");
    }
}
