/*
 * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
 */

import { PlexAPICore } from "../core.js";
import { encodeSimple } from "../lib/encodings.js";
import * as M from "../lib/matchers.js";
import { compactMap } from "../lib/primitives.js";
import { safeParse } from "../lib/schemas.js";
import { RequestOptions } from "../lib/sdks.js";
import { pathToFunc } from "../lib/url.js";
import {
  ConnectionError,
  InvalidRequestError,
  RequestAbortedError,
  RequestTimeoutError,
  UnexpectedClientError,
} from "../sdk/models/errors/httpclienterrors.js";
import * as errors from "../sdk/models/errors/index.js";
import { SDKError } from "../sdk/models/errors/sdkerror.js";
import { SDKValidationError } from "../sdk/models/errors/sdkvalidationerror.js";
import { GetUsersServerList } from "../sdk/models/operations/getusers.js";
import * as operations from "../sdk/models/operations/index.js";
import { Result } from "../sdk/types/fp.js";

/**
 * Get list of all connected users
 *
 * @remarks
 * Get list of all users that are friends and have library access with the provided Plex authentication token
 */
export async function usersGetUsers(
  client: PlexAPICore,
  request: operations.GetUsersRequest,
  options?: RequestOptions,
): Promise<
  Result<
    operations.GetUsersResponse,
    | errors.GetUsersBadRequest
    | errors.GetUsersUnauthorized
    | SDKError
    | SDKValidationError
    | UnexpectedClientError
    | InvalidRequestError
    | RequestAbortedError
    | RequestTimeoutError
    | ConnectionError
  >
> {
  const parsed = safeParse(
    request,
    (value) => operations.GetUsersRequest$outboundSchema.parse(value),
    "Input validation failed",
  );
  if (!parsed.ok) {
    return parsed;
  }
  const payload = parsed.value;
  const body = null;

  const baseURL = options?.serverURL
    || pathToFunc(GetUsersServerList[0], { charEncoding: "percent" })();

  const path = pathToFunc("/users")();

  const headers = new Headers(compactMap({
    Accept: "application/xml",
    "X-Plex-Features": encodeSimple("X-Plex-Features", payload.ClientFeatures, {
      explode: false,
      charEncoding: "none",
    }),
    "X-Plex-Client-Identifier": encodeSimple(
      "X-Plex-Client-Identifier",
      payload.ClientID,
      { explode: false, charEncoding: "none" },
    ),
    "X-Plex-Product": encodeSimple("X-Plex-Product", payload.ClientName, {
      explode: false,
      charEncoding: "none",
    }),
    "X-Plex-Version": encodeSimple("X-Plex-Version", payload.ClientVersion, {
      explode: false,
      charEncoding: "none",
    }),
    "X-Plex-Device-Name": encodeSimple(
      "X-Plex-Device-Name",
      payload.DeviceName,
      { explode: false, charEncoding: "none" },
    ),
    "X-Plex-Device": encodeSimple("X-Plex-Device", payload.DeviceNickname, {
      explode: false,
      charEncoding: "none",
    }),
    "X-Plex-Device-Screen-Resolution": encodeSimple(
      "X-Plex-Device-Screen-Resolution",
      payload.DeviceScreenResolution,
      { explode: false, charEncoding: "none" },
    ),
    "X-Plex-Model": encodeSimple("X-Plex-Model", payload.Model, {
      explode: false,
      charEncoding: "none",
    }),
    "X-Plex-Platform": encodeSimple("X-Plex-Platform", payload.Platform, {
      explode: false,
      charEncoding: "none",
    }),
    "X-Plex-Platform-Version": encodeSimple(
      "X-Plex-Platform-Version",
      payload.PlatformVersion,
      { explode: false, charEncoding: "none" },
    ),
    "X-Plex-Language": encodeSimple(
      "X-Plex-Language",
      payload["X-Plex-Language"],
      { explode: false, charEncoding: "none" },
    ),
    "X-Plex-Session-Id": encodeSimple(
      "X-Plex-Session-Id",
      payload["X-Plex-Session-Id"],
      { explode: false, charEncoding: "none" },
    ),
    "X-Plex-Token": encodeSimple("X-Plex-Token", payload["X-Plex-Token"], {
      explode: false,
      charEncoding: "none",
    }),
  }));

  const context = {
    operationID: "get-users",
    oAuth2Scopes: [],

    resolvedSecurity: null,

    securitySource: null,
    retryConfig: options?.retries
      || client._options.retryConfig
      || { strategy: "none" },
    retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"],
  };

  const requestRes = client._createRequest(context, {
    method: "GET",
    baseURL: baseURL,
    path: path,
    headers: headers,
    body: body,
    timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1,
  }, options);
  if (!requestRes.ok) {
    return requestRes;
  }
  const req = requestRes.value;

  const doResult = await client._do(req, {
    context,
    errorCodes: ["400", "401", "4XX", "5XX"],
    retryConfig: context.retryConfig,
    retryCodes: context.retryCodes,
  });
  if (!doResult.ok) {
    return doResult;
  }
  const response = doResult.value;

  const responseFields = {
    ContentType: response.headers.get("content-type")
      ?? "application/octet-stream",
    StatusCode: response.status,
    RawResponse: response,
    Headers: {},
  };

  const [result] = await M.match<
    operations.GetUsersResponse,
    | errors.GetUsersBadRequest
    | errors.GetUsersUnauthorized
    | SDKError
    | SDKValidationError
    | UnexpectedClientError
    | InvalidRequestError
    | RequestAbortedError
    | RequestTimeoutError
    | ConnectionError
  >(
    M.bytes(200, operations.GetUsersResponse$inboundSchema, {
      ctype: "application/xml",
      key: "Body",
    }),
    M.jsonErr(400, errors.GetUsersBadRequest$inboundSchema),
    M.jsonErr(401, errors.GetUsersUnauthorized$inboundSchema),
    M.fail("4XX"),
    M.fail("5XX"),
  )(response, { extraFields: responseFields });
  if (!result.ok) {
    return result;
  }

  return result;
}
