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

import * as core from "../../../../core";
import * as Rivet from "../../../index";
import * as serializers from "../../../../serialization/index";
import urlJoin from "url-join";
import * as errors from "../../../../errors/index";

export declare namespace Runners {
    export interface Options {
        environment: core.Supplier<string>;
        /** Specify a custom URL to connect the client to. */
        baseUrl?: core.Supplier<string>;
        token: core.Supplier<core.BearerToken>;
        fetcher?: core.FetchFunction;
    }

    export interface RequestOptions {
        /** The maximum time to wait for a response in seconds. */
        timeoutInSeconds?: number;
        /** The number of times to retry the request. Defaults to 2. */
        maxRetries?: number;
        /** A hook to abort the request. */
        abortSignal?: AbortSignal;
        /** Additional headers to include in the request. */
        headers?: Record<string, string>;
    }
}

export class Runners {
    constructor(protected readonly _options: Runners.Options) {}

    /**
     * @param {Rivet.RunnersListRequest} request
     * @param {Runners.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.runners.list({
     *         namespace: "namespace"
     *     })
     */
    public async list(
        request: Rivet.RunnersListRequest,
        requestOptions?: Runners.RequestOptions,
    ): Promise<Rivet.RunnersListResponse> {
        const { namespace, name, runnerIds, runnerId, includeStopped, limit, cursor } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams["namespace"] = namespace;
        if (name != null) {
            _queryParams["name"] = name;
        }

        if (runnerIds != null) {
            _queryParams["runner_ids"] = runnerIds;
        }

        if (runnerId != null) {
            if (Array.isArray(runnerId)) {
                _queryParams["runner_id"] = runnerId.map((item) =>
                    serializers.RivetId.jsonOrThrow(item, { unrecognizedObjectKeys: "strip" }),
                );
            } else {
                _queryParams["runner_id"] = runnerId;
            }
        }

        if (includeStopped != null) {
            _queryParams["include_stopped"] = includeStopped.toString();
        }

        if (limit != null) {
            _queryParams["limit"] = limit.toString();
        }

        if (cursor != null) {
            _queryParams["cursor"] = cursor;
        }

        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: urlJoin(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)),
                "runners",
            ),
            method: "GET",
            headers: {
                Authorization: await this._getAuthorizationHeader(),
                "X-Fern-Language": "JavaScript",
                "X-Fern-Runtime": core.RUNTIME.type,
                "X-Fern-Runtime-Version": core.RUNTIME.version,
                ...requestOptions?.headers,
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 180000,
            maxRetries: requestOptions?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
        });
        if (_response.ok) {
            return serializers.RunnersListResponse.parseOrThrow(_response.body, {
                unrecognizedObjectKeys: "passthrough",
                allowUnrecognizedUnionMembers: true,
                allowUnrecognizedEnumValues: true,
                skipValidation: true,
                breadcrumbsPrefix: ["response"],
            });
        }

        if (_response.error.reason === "status-code") {
            throw new errors.RivetError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
            });
        }

        switch (_response.error.reason) {
            case "non-json":
                throw new errors.RivetError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.rawBody,
                });
            case "timeout":
                throw new errors.RivetTimeoutError("Timeout exceeded when calling GET /runners.");
            case "unknown":
                throw new errors.RivetError({
                    message: _response.error.errorMessage,
                });
        }
    }

    /**
     * 2 round trips:
     *
     * - GET /runners/names (fanout)
     * - [api-peer] namespace::ops::resolve_for_name_global
     *
     * @param {Rivet.RunnersListNamesRequest} request
     * @param {Runners.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.runners.listNames({
     *         namespace: "namespace"
     *     })
     */
    public async listNames(
        request: Rivet.RunnersListNamesRequest,
        requestOptions?: Runners.RequestOptions,
    ): Promise<Rivet.RunnersListNamesResponse> {
        const { namespace, limit, cursor } = request;
        const _queryParams: Record<string, string | string[] | object | object[] | null> = {};
        _queryParams["namespace"] = namespace;
        if (limit != null) {
            _queryParams["limit"] = limit.toString();
        }

        if (cursor != null) {
            _queryParams["cursor"] = cursor;
        }

        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: urlJoin(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)),
                "runners/names",
            ),
            method: "GET",
            headers: {
                Authorization: await this._getAuthorizationHeader(),
                "X-Fern-Language": "JavaScript",
                "X-Fern-Runtime": core.RUNTIME.type,
                "X-Fern-Runtime-Version": core.RUNTIME.version,
                ...requestOptions?.headers,
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 180000,
            maxRetries: requestOptions?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
        });
        if (_response.ok) {
            return serializers.RunnersListNamesResponse.parseOrThrow(_response.body, {
                unrecognizedObjectKeys: "passthrough",
                allowUnrecognizedUnionMembers: true,
                allowUnrecognizedEnumValues: true,
                skipValidation: true,
                breadcrumbsPrefix: ["response"],
            });
        }

        if (_response.error.reason === "status-code") {
            throw new errors.RivetError({
                statusCode: _response.error.statusCode,
                body: _response.error.body,
            });
        }

        switch (_response.error.reason) {
            case "non-json":
                throw new errors.RivetError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.rawBody,
                });
            case "timeout":
                throw new errors.RivetTimeoutError("Timeout exceeded when calling GET /runners/names.");
            case "unknown":
                throw new errors.RivetError({
                    message: _response.error.errorMessage,
                });
        }
    }

    protected async _getAuthorizationHeader(): Promise<string> {
        return `Bearer ${await core.Supplier.get(this._options.token)}`;
    }
}
