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

    export interface RequestOptions extends BaseRequestOptions {}
}

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

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

    /**
     * Returns all projects in the organization.
     *
     * @param {ProjectsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.UnauthorizedError}
     *
     * @example
     *     await client.projects.list()
     */
    public list(requestOptions?: ProjectsClient.RequestOptions): core.HttpResponsePromise<LatitudeApi.ProjectList> {
        return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
    }

    private async __list(
        requestOptions?: ProjectsClient.RequestOptions,
    ): Promise<core.WithRawResponse<LatitudeApi.ProjectList>> {
        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/projects",
            ),
            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.ProjectList, 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/projects");
    }

    /**
     * Creates a new project within the organization.
     *
     * @param {LatitudeApi.CreateProjectBody} request
     * @param {ProjectsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.BadRequestError}
     * @throws {@link LatitudeApi.UnauthorizedError}
     * @throws {@link LatitudeApi.NotFoundError}
     *
     * @example
     *     await client.projects.create({
     *         name: "name"
     *     })
     */
    public create(
        request: LatitudeApi.CreateProjectBody,
        requestOptions?: ProjectsClient.RequestOptions,
    ): core.HttpResponsePromise<LatitudeApi.Project> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: LatitudeApi.CreateProjectBody,
        requestOptions?: ProjectsClient.RequestOptions,
    ): Promise<core.WithRawResponse<LatitudeApi.Project>> {
        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/projects",
            ),
            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.Project, 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/projects");
    }

    /**
     * Returns a single project by slug.
     *
     * @param {string} projectSlug - Project slug (human-readable identifier)
     * @param {ProjectsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.UnauthorizedError}
     * @throws {@link LatitudeApi.NotFoundError}
     *
     * @example
     *     await client.projects.get("projectSlug")
     */
    public get(
        projectSlug: string,
        requestOptions?: ProjectsClient.RequestOptions,
    ): core.HttpResponsePromise<LatitudeApi.Project> {
        return core.HttpResponsePromise.fromPromise(this.__get(projectSlug, requestOptions));
    }

    private async __get(
        projectSlug: string,
        requestOptions?: ProjectsClient.RequestOptions,
    ): Promise<core.WithRawResponse<LatitudeApi.Project>> {
        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/projects/${core.url.encodePathParam(projectSlug)}`,
            ),
            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.Project, 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, "GET", "/v1/projects/{projectSlug}");
    }

    /**
     * Soft-deletes a project by slug.
     *
     * @param {string} projectSlug - Project slug (human-readable identifier)
     * @param {ProjectsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.UnauthorizedError}
     * @throws {@link LatitudeApi.NotFoundError}
     *
     * @example
     *     await client.projects.delete("projectSlug")
     */
    public delete(projectSlug: string, requestOptions?: ProjectsClient.RequestOptions): core.HttpResponsePromise<void> {
        return core.HttpResponsePromise.fromPromise(this.__delete(projectSlug, requestOptions));
    }

    private async __delete(
        projectSlug: string,
        requestOptions?: ProjectsClient.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/projects/${core.url.encodePathParam(projectSlug)}`,
            ),
            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/projects/{projectSlug}");
    }

    /**
     * Updates a project's name and/or description.
     *
     * @param {string} projectSlug - Project slug (human-readable identifier)
     * @param {LatitudeApi.UpdateProjectBody} request
     * @param {ProjectsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link LatitudeApi.BadRequestError}
     * @throws {@link LatitudeApi.UnauthorizedError}
     * @throws {@link LatitudeApi.NotFoundError}
     *
     * @example
     *     await client.projects.update("projectSlug")
     */
    public update(
        projectSlug: string,
        request: LatitudeApi.UpdateProjectBody = {},
        requestOptions?: ProjectsClient.RequestOptions,
    ): core.HttpResponsePromise<LatitudeApi.Project> {
        return core.HttpResponsePromise.fromPromise(this.__update(projectSlug, request, requestOptions));
    }

    private async __update(
        projectSlug: string,
        request: LatitudeApi.UpdateProjectBody = {},
        requestOptions?: ProjectsClient.RequestOptions,
    ): Promise<core.WithRawResponse<LatitudeApi.Project>> {
        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/projects/${core.url.encodePathParam(projectSlug)}`,
            ),
            method: "PATCH",
            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.Project, 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, "PATCH", "/v1/projects/{projectSlug}");
    }
}
