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

import * as z from "zod";
import { PlexAPICore } from "../core.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 { 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 * as operations from "../sdk/models/operations/index.js";
import { APICall, APIPromise } from "../sdk/types/async.js";
import { Result } from "../sdk/types/fp.js";

/**
 * Logging a multi-line message
 *
 * @remarks
 * This endpoint allows for the batch addition of log entries to the main Plex Media Server log.
 * It accepts a text/plain request body, where each line represents a distinct log entry.
 * Each log entry consists of URL-encoded key-value pairs, specifying log attributes such as 'level', 'message', and 'source'.
 *
 * Log entries are separated by a newline character (`\n`).
 * Each entry's parameters should be URL-encoded to ensure accurate parsing and handling of special characters.
 * This method is efficient for logging multiple entries in a single API call, reducing the overhead of multiple individual requests.
 *
 * The 'level' parameter specifies the log entry's severity or importance, with the following integer values:
 * - `0`: Error - Critical issues that require immediate attention.
 * - `1`: Warning - Important events that are not critical but may indicate potential issues.
 * - `2`: Info - General informational messages about system operation.
 * - `3`: Debug - Detailed information useful for debugging purposes.
 * - `4`: Verbose - Highly detailed diagnostic information for in-depth analysis.
 *
 * The 'message' parameter contains the log text, and 'source' identifies the log message's origin (e.g., an application name or module).
 *
 * Example of a single log entry format:
 * `level=4&message=Sample%20log%20entry&source=applicationName`
 *
 * Ensure each parameter is properly URL-encoded to avoid interpretation issues.
 */
export function logLogMultiLine(
  client: PlexAPICore,
  request: string,
  options?: RequestOptions,
): APIPromise<
  Result<
    operations.LogMultiLineResponse,
    | errors.LogMultiLineBadRequest
    | errors.LogMultiLineUnauthorized
    | SDKError
    | SDKValidationError
    | UnexpectedClientError
    | InvalidRequestError
    | RequestAbortedError
    | RequestTimeoutError
    | ConnectionError
  >
> {
  return new APIPromise($do(
    client,
    request,
    options,
  ));
}

async function $do(
  client: PlexAPICore,
  request: string,
  options?: RequestOptions,
): Promise<
  [
    Result<
      operations.LogMultiLineResponse,
      | errors.LogMultiLineBadRequest
      | errors.LogMultiLineUnauthorized
      | SDKError
      | SDKValidationError
      | UnexpectedClientError
      | InvalidRequestError
      | RequestAbortedError
      | RequestTimeoutError
      | ConnectionError
    >,
    APICall,
  ]
> {
  const parsed = safeParse(
    request,
    (value) => z.string().parse(value),
    "Input validation failed",
  );
  if (!parsed.ok) {
    return [parsed, { status: "invalid" }];
  }
  const payload = parsed.value;
  const body = payload;

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

  const headers = new Headers(compactMap({
    "Content-Type": "text/plain",
    Accept: "application/json",
  }));

  const secConfig = await extractSecurity(client._options.accessToken);
  const securityInput = secConfig == null ? {} : { accessToken: secConfig };
  const requestSecurity = resolveGlobalSecurity(securityInput);

  const context = {
    baseURL: options?.serverURL ?? client._baseURL ?? "",
    operationID: "logMultiLine",
    oAuth2Scopes: [],

    resolvedSecurity: requestSecurity,

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

  const requestRes = client._createRequest(context, {
    security: requestSecurity,
    method: "POST",
    baseURL: options?.serverURL,
    path: path,
    headers: headers,
    body: body,
    timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1,
  }, options);
  if (!requestRes.ok) {
    return [requestRes, { status: "invalid" }];
  }
  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, { status: "request-error", request: req }];
  }
  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.LogMultiLineResponse,
    | errors.LogMultiLineBadRequest
    | errors.LogMultiLineUnauthorized
    | SDKError
    | SDKValidationError
    | UnexpectedClientError
    | InvalidRequestError
    | RequestAbortedError
    | RequestTimeoutError
    | ConnectionError
  >(
    M.nil(200, operations.LogMultiLineResponse$inboundSchema),
    M.jsonErr(400, errors.LogMultiLineBadRequest$inboundSchema),
    M.jsonErr(401, errors.LogMultiLineUnauthorized$inboundSchema),
    M.fail("4XX"),
    M.fail("5XX"),
  )(response, { extraFields: responseFields });
  if (!result.ok) {
    return [result, { status: "complete", request: req, response }];
  }

  return [result, { status: "complete", request: req, response }];
}
