// 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 ChatsClient {
    export type Options = BaseClientOptions;

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * @beta This endpoint is in pre-release and may change.
     *
     * @param {Vapi.ListChatsRequest} request
     * @param {ChatsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.chats.list({
     *         assistantIdAny: "assistant-1,assistant-2,assistant-3"
     *     })
     */
    public list(
        request: Vapi.ListChatsRequest = {},
        requestOptions?: ChatsClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.ChatPaginatedResponse> {
        return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions));
    }

    private async __list(
        request: Vapi.ListChatsRequest = {},
        requestOptions?: ChatsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.ChatPaginatedResponse>> {
        const {
            id,
            assistantId,
            assistantIdAny,
            squadId,
            sessionId,
            previousChatId,
            page,
            sortOrder,
            limit,
            createdAtGt,
            createdAtLt,
            createdAtGe,
            createdAtLe,
            updatedAtGt,
            updatedAtLt,
            updatedAtGe,
            updatedAtLe,
        } = request;
        const _queryParams: Record<string, unknown> = {
            id,
            assistantId,
            assistantIdAny,
            squadId,
            sessionId,
            previousChatId,
            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,
                "chat",
            ),
            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.ChatPaginatedResponse, 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", "/chat");
    }

    /**
     * @beta This endpoint is in pre-release and may change.
     *
     * Creates a new chat with optional SMS delivery via transport field. Requires at least one of: assistantId/assistant, sessionId, or previousChatId. Note: sessionId and previousChatId are mutually exclusive. Transport field enables SMS delivery with two modes: (1) New conversation - provide transport.phoneNumberId and transport.customer to create a new session, (2) Existing conversation - provide sessionId to use existing session data. Cannot specify both sessionId and transport fields together. The transport.useLLMGeneratedMessageForOutbound flag controls whether input is processed by LLM (true, default) or forwarded directly as SMS (false).
     *
     * @param {Vapi.CreateChatDto} request
     * @param {ChatsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.chats.create({
     *         input: "input"
     *     })
     */
    public create(
        request: Vapi.CreateChatDto,
        requestOptions?: ChatsClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.CreateChatsResponse> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: Vapi.CreateChatDto,
        requestOptions?: ChatsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.CreateChatsResponse>> {
        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,
                "chat",
            ),
            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.CreateChatsResponse, 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", "/chat");
    }

    /**
     * @beta This endpoint is in pre-release and may change.
     *
     * @param {Vapi.GetChatsRequest} request
     * @param {ChatsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.chats.get({
     *         id: "id"
     *     })
     */
    public get(
        request: Vapi.GetChatsRequest,
        requestOptions?: ChatsClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.Chat> {
        return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions));
    }

    private async __get(
        request: Vapi.GetChatsRequest,
        requestOptions?: ChatsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.Chat>> {
        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,
                `chat/${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.Chat, 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", "/chat/{id}");
    }

    /**
     * @beta This endpoint is in pre-release and may change.
     *
     * @param {Vapi.DeleteChatsRequest} request
     * @param {ChatsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.chats.delete({
     *         id: "id"
     *     })
     */
    public delete(
        request: Vapi.DeleteChatsRequest,
        requestOptions?: ChatsClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.Chat> {
        return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions));
    }

    private async __delete(
        request: Vapi.DeleteChatsRequest,
        requestOptions?: ChatsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.Chat>> {
        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,
                `chat/${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.Chat, 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", "/chat/{id}");
    }

    /**
     * @beta This endpoint is in pre-release and may change.
     *
     * @param {Vapi.OpenAiResponsesRequest} request
     * @param {ChatsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @example
     *     await client.chats.createResponse({
     *         input: "input"
     *     })
     */
    public createResponse(
        request: Vapi.OpenAiResponsesRequest,
        requestOptions?: ChatsClient.RequestOptions,
    ): core.HttpResponsePromise<Vapi.CreateResponseChatsResponse> {
        return core.HttpResponsePromise.fromPromise(this.__createResponse(request, requestOptions));
    }

    private async __createResponse(
        request: Vapi.OpenAiResponsesRequest,
        requestOptions?: ChatsClient.RequestOptions,
    ): Promise<core.WithRawResponse<Vapi.CreateResponseChatsResponse>> {
        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,
                "chat/responses",
            ),
            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.CreateResponseChatsResponse, 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", "/chat/responses");
    }
}
