// 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 type * as Vapi from "../../../index.js";

export declare namespace PhoneNumbersClient {
    export type Options = BaseClientOptions;

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * @param {Vapi.ListPhoneNumbersRequest} request
     * @param {PhoneNumbersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.phoneNumbers.list()
     */
    public list(
        request: Vapi.ListPhoneNumbersRequest = {},
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.ListPhoneNumbersResponseItem[]> {
        return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions));
    }

    private async __list(
        request: Vapi.ListPhoneNumbersRequest = {},
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.ListPhoneNumbersResponseItem[]>> {
        const {
            limit,
            createdAtGt,
            createdAtLt,
            createdAtGe,
            createdAtLe,
            updatedAtGt,
            updatedAtLt,
            updatedAtGe,
            updatedAtLe,
        } = request;
        const _queryParams: Record<string, unknown> = {
            limit,
            createdAtGt: createdAtGt != null ? createdAtGt : undefined,
            createdAtLt: createdAtLt != null ? createdAtLt : undefined,
            createdAtGe: createdAtGe != null ? createdAtGe : undefined,
            createdAtLe: createdAtLe != null ? createdAtLe : undefined,
            updatedAtGt: updatedAtGt != null ? updatedAtGt : undefined,
            updatedAtLt: updatedAtLt != null ? updatedAtLt : undefined,
            updatedAtGe: updatedAtGe != null ? updatedAtGe : undefined,
            updatedAtLe: updatedAtLe != null ? updatedAtLe : undefined,
        };
        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 (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.VapiEnvironment.Default,
                "phone-number",
            ),
            method: "GET",
            headers: _headers,
            queryParameters: { ..._queryParams, ...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 Vapi.ListPhoneNumbersResponseItem[], rawResponse: _response.rawResponse };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/phone-number");
    }

    /**
     * @param {Vapi.CreatePhoneNumbersRequest} request
     * @param {PhoneNumbersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.phoneNumbers.create({
     *         provider: "byo-phone-number",
     *         credentialId: "credentialId"
     *     })
     */
    public create(
        request: Vapi.CreatePhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.CreatePhoneNumbersResponse> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: Vapi.CreatePhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.CreatePhoneNumbersResponse>> {
        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 (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.VapiEnvironment.Default,
                "phone-number",
            ),
            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 Vapi.CreatePhoneNumbersResponse, rawResponse: _response.rawResponse };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/phone-number");
    }

    /**
     * @param {Vapi.PhoneNumberControllerFindAllPaginatedRequest} request
     * @param {PhoneNumbersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.phoneNumbers.phoneNumberControllerFindAllPaginated()
     */
    public phoneNumberControllerFindAllPaginated(
        request: Vapi.PhoneNumberControllerFindAllPaginatedRequest = {},
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.PhoneNumberPaginatedResponse> {
        return core.HttpResponsePromise.fromPromise(
            this.__phoneNumberControllerFindAllPaginated(request, requestOptions),
        );
    }

    private async __phoneNumberControllerFindAllPaginated(
        request: Vapi.PhoneNumberControllerFindAllPaginatedRequest = {},
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.PhoneNumberPaginatedResponse>> {
        const {
            search,
            page,
            sortOrder,
            limit,
            createdAtGt,
            createdAtLt,
            createdAtGe,
            createdAtLe,
            updatedAtGt,
            updatedAtLt,
            updatedAtGe,
            updatedAtLe,
        } = request;
        const _queryParams: Record<string, unknown> = {
            search,
            page,
            sortOrder: sortOrder != null ? sortOrder : undefined,
            limit,
            createdAtGt: createdAtGt != null ? createdAtGt : undefined,
            createdAtLt: createdAtLt != null ? createdAtLt : undefined,
            createdAtGe: createdAtGe != null ? createdAtGe : undefined,
            createdAtLe: createdAtLe != null ? createdAtLe : undefined,
            updatedAtGt: updatedAtGt != null ? updatedAtGt : undefined,
            updatedAtLt: updatedAtLt != null ? updatedAtLt : undefined,
            updatedAtGe: updatedAtGe != null ? updatedAtGe : undefined,
            updatedAtLe: updatedAtLe != null ? updatedAtLe : undefined,
        };
        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 (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.VapiEnvironment.Default,
                "v2/phone-number",
            ),
            method: "GET",
            headers: _headers,
            queryParameters: { ..._queryParams, ...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 Vapi.PhoneNumberPaginatedResponse, rawResponse: _response.rawResponse };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v2/phone-number");
    }

    /**
     * @param {Vapi.GetPhoneNumbersRequest} request
     * @param {PhoneNumbersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.phoneNumbers.get({
     *         id: "id"
     *     })
     */
    public get(
        request: Vapi.GetPhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.GetPhoneNumbersResponse> {
        return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions));
    }

    private async __get(
        request: Vapi.GetPhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.GetPhoneNumbersResponse>> {
        const { id } = request;
        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 (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.VapiEnvironment.Default,
                `phone-number/${core.url.encodePathParam(id)}`,
            ),
            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 Vapi.GetPhoneNumbersResponse, rawResponse: _response.rawResponse };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/phone-number/{id}");
    }

    /**
     * @param {Vapi.DeletePhoneNumbersRequest} request
     * @param {PhoneNumbersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.phoneNumbers.delete({
     *         id: "id"
     *     })
     */
    public delete(
        request: Vapi.DeletePhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.DeletePhoneNumbersResponse> {
        return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions));
    }

    private async __delete(
        request: Vapi.DeletePhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.DeletePhoneNumbersResponse>> {
        const { id } = request;
        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 (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.VapiEnvironment.Default,
                `phone-number/${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: _response.body as Vapi.DeletePhoneNumbersResponse, rawResponse: _response.rawResponse };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/phone-number/{id}");
    }

    /**
     * @param {Vapi.UpdatePhoneNumbersRequest} request
     * @param {PhoneNumbersClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.phoneNumbers.update({
     *         id: "id",
     *         body: {
     *             provider: "byo-phone-number"
     *         }
     *     })
     */
    public update(
        request: Vapi.UpdatePhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.UpdatePhoneNumbersResponse> {
        return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions));
    }

    private async __update(
        request: Vapi.UpdatePhoneNumbersRequest,
        requestOptions?: PhoneNumbersClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.UpdatePhoneNumbersResponse>> {
        const { id, body: _body } = request;
        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 (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)) ??
                    environments.VapiEnvironment.Default,
                `phone-number/${core.url.encodePathParam(id)}`,
            ),
            method: "PATCH",
            headers: _headers,
            contentType: "application/json",
            queryParameters: requestOptions?.queryParams,
            requestType: "json",
            body: _body,
            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 Vapi.UpdatePhoneNumbersResponse, rawResponse: _response.rawResponse };
        }

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

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "PATCH", "/phone-number/{id}");
    }
}
