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

import { PlexAPICore } from "../core.js";
import { encodeFormQuery, encodeSimple } from "../lib/encodings.js";
import * as M from "../lib/matchers.js";
import { safeParse } from "../lib/schemas.js";
import { RequestOptions } from "../lib/sdks.js";
import { extractSecurity, resolveGlobalSecurity } from "../lib/security.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 { GetWatchListServerList } from "../sdk/models/operations/getwatchlist.js";
import * as operations from "../sdk/models/operations/index.js";
import { Result } from "../sdk/types/fp.js";

/**
 * Get User Watchlist
 *
 * @remarks
 * Get User Watchlist
 */
export async function watchlistGetWatchList(
  client: PlexAPICore,
  request: operations.GetWatchListRequest,
  options?: RequestOptions & { serverURL?: string },
): Promise<
  Result<
    operations.GetWatchListResponse,
    | errors.GetWatchListBadRequest
    | errors.GetWatchListUnauthorized
    | SDKError
    | SDKValidationError
    | UnexpectedClientError
    | InvalidRequestError
    | RequestAbortedError
    | RequestTimeoutError
    | ConnectionError
  >
> {
  const input = request;

  const parsed = safeParse(
    input,
    (value) => operations.GetWatchListRequest$outboundSchema.parse(value),
    "Input validation failed",
  );
  if (!parsed.ok) {
    return parsed;
  }
  const payload = parsed.value;
  const body = null;

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

  const pathParams = {
    filter: encodeSimple("filter", payload.filter, {
      explode: false,
      charEncoding: "percent",
    }),
  };

  const path = pathToFunc("/library/sections/watchlist/{filter}")(pathParams);

  const query = encodeFormQuery({
    "includeCollections": payload.includeCollections,
    "includeExternalMedia": payload.includeExternalMedia,
    "libtype": payload.libtype,
    "maxresults": payload.maxresults,
    "sort": payload.sort,
    "X-Plex-Container-Size": payload["X-Plex-Container-Size"],
    "X-Plex-Container-Start": payload["X-Plex-Container-Start"],
  });

  const headers = new Headers({
    Accept: "application/json",
    "X-Plex-Token": encodeSimple("X-Plex-Token", payload["X-Plex-Token"], {
      explode: false,
      charEncoding: "none",
    }),
  });

  const secConfig = await extractSecurity(client._options.accessToken);
  const securityInput = secConfig == null ? {} : { accessToken: secConfig };
  const context = {
    operationID: "get-watch-list",
    oAuth2Scopes: [],
    securitySource: client._options.accessToken,
  };
  const requestSecurity = resolveGlobalSecurity(securityInput);

  const requestRes = client._createRequest(context, {
    security: requestSecurity,
    method: "GET",
    baseURL: baseURL,
    path: path,
    headers: headers,
    query: query,
    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: options?.retries
      || client._options.retryConfig,
    retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"],
  });
  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.GetWatchListResponse,
    | errors.GetWatchListBadRequest
    | errors.GetWatchListUnauthorized
    | SDKError
    | SDKValidationError
    | UnexpectedClientError
    | InvalidRequestError
    | RequestAbortedError
    | RequestTimeoutError
    | ConnectionError
  >(
    M.json(200, operations.GetWatchListResponse$inboundSchema, {
      key: "object",
    }),
    M.jsonErr(400, errors.GetWatchListBadRequest$inboundSchema),
    M.jsonErr(401, errors.GetWatchListUnauthorized$inboundSchema),
    M.fail(["4XX", "5XX"]),
  )(response, { extraFields: responseFields });
  if (!result.ok) {
    return result;
  }

  return result;
}
