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

import { IamClientCore } from "../core.js";
import { encodeJSON, encodeSimple } from "../lib/encodings.js";
import { matchStatusCode } from "../lib/http.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 * as components from "../models/components/index.js";
import {
  ConnectionError,
  InvalidRequestError,
  RequestAbortedError,
  RequestTimeoutError,
  UnexpectedClientError,
} from "../models/errors/httpclienterrors.js";
import { IamClientError } from "../models/errors/iamclienterror.js";
import * as errors from "../models/errors/index.js";
import { ResponseValidationError } from "../models/errors/responsevalidationerror.js";
import { SDKValidationError } from "../models/errors/sdkvalidationerror.js";
import * as operations from "../models/operations/index.js";
import { APICall, APIPromise } from "../types/async.js";
import { Result } from "../types/fp.js";

/**
 * Create new bulk job with presigned URLs direct to Azure Blob Store
 *
 * @remarks
 * Create a new job, give presigned URLs back, the client will upload to Azure Blob Store directly.
 *
 * **Important Upload Workflow**:
 * 1. Call this endpoint to create a job and receive upload URLs
 * 2. For each document in the response's `_embedded.documents` array, extract the `upload_document` URL from `_actions`
 * 3. Upload your document file to each URL using an HTTP PUT request with the document content as binary data
 * 4. After all documents are uploaded, call the `/actions/complete` endpoint to finalize the job
 * 5. Use the GET endpoint to monitor job progress
 *
 * **Example response structure**:
 * ```json
 * {
 *   "_embedded": {
 *     "documents": [
 *       {
 *         "id": "8c566d26-e7fb-4b7e-870c-1d0fb8df9084",
 *         "sequence": 1,
 *         "_actions": {
 *           "upload_document": "https://docupstoragewestwu3dsto.blob.core.windows.net/..."
 *         }
 *       }
 *     ]
 *   }
 * }
 * ```
 *
 * **Azure Blob Storage Upload Instructions**:
 *
 * Use the pre-signed URL from step 2 to upload your document directly to Azure Blob Storage:
 *
 * ```
 * PUT [pre-signed URL from _actions.upload_document]
 *
 * Headers:
 * - x-ms-blob-type: BlockBlob (Required)
 * - x-ms-meta-filename: YourDocumentName.pdf (Recommended)
 * - Content-Type: application/pdf (Required)
 * - x-ms-meta-metadata: <stringified JSON metadata> (Optional)
 *
 * Body: [Your document binary data]
 * ```
 *
 * **Important Notes**:
 * - The `upload_document` URLs are pre-signed Azure Blob Storage URLs with time-limited validity (8 hours)
 * - No Auth header is needed
 * - The `x-ms-meta-filename` header should contain your original document filename
 * - The `x-ms-blob-type` must be set to `BlockBlob`
 * - Setting the `Content-Type` header is recommended to match your document type
 * - If `Content-Type` is not specified, Azure defaults to `application/octet-stream`
 * - The `x-ms-meta-metadata` header is optional and allows you to attach metadata to the newly created agreement at upload time. See **Applying Metadata to Agreements** below for details
 *
 * **Applying Metadata to Agreements**:
 *
 * You may include metadata alongside the document bytes during upload. This metadata will be directly applied to the
 * newly created agreement. To do this, include the `x-ms-meta-metadata` header on the PUT operation with a stringified
 * JSON value.
 *
 * The JSON schema for this header follows the same structure as the standard Agreement PATCH request body.
 *
 * **Example metadata JSON**:
 * ```json
 * {
 *   "provisions": {
 *     "jurisdiction": "California",
 *     "payment_terms_due_date": "OTHER"
 *   },
 *   "custom_provisions": {
 *     "c_ClientId": "value"
 *   },
 *   "linked_data": [
 *     {
 *       "application_name": "Salesforce",
 *       "object_name": "Account",
 *       "record_id": "579386BF-C8EA-4673-AE0E-E2F922B09DC5"
 *     },
 *     {
 *       "application_name": "Dynamics",
 *       "object_name": "Account",
 *       "record_id": "514CEAFB-1AC7-43FF-9E88-24CB15150963"
 *     }
 *   ]
 * }
 * ```
 *
 * **Stringified header value**:
 *
 * The JSON must be stringified before being set as the header value. For example, the above JSON would become:
 * ```
 * x-ms-meta-metadata: "{\"provisions\":{\"jurisdiction\":\"California\",\"payment_terms_due_date\":\"OTHER\"},\"custom_provisions\":{\"c_ClientId\":\"value\"},\"linked_data\":[{\"application_name\":\"Salesforce\",\"object_name\":\"Account\",\"record_id\":\"579386BF-C8EA-4673-AE0E-E2F922B09DC5\"},{\"application_name\":\"Dynamics\",\"object_name\":\"Account\",\"record_id\":\"514CEAFB-1AC7-43FF-9E88-24CB15150963\"}]}"
 * ```
 *
 * **Metadata Notes**:
 * - The `x-ms-meta-metadata` header is entirely optional. If omitted, the agreement is created with AI-extracted values only
 * - The JSON must be stringified (serialized to a single string) before being placed in the header value
 * - The metadata payload follows the same schema as the Agreement PATCH endpoint request body
 * - Values provided via metadata will be applied to the agreement after creation, overriding any AI-extracted values for the same fields
 *
 * **Firewall & Network Configuration**:
 *
 * If your organization uses firewalls or network restrictions, you may need to whitelist the following Azure Blob Storage domains
 * to ensure successful document uploads. The upload URLs returned by this API will use one of these domains based on your
 * account's geographic region:
 *
 * **Primary Storage Endpoints**:
 * - `https://docupstorageaustauepsto.blob.core.windows.net/`
 * - `https://docupstoragecanacacpsto.blob.core.windows.net/`
 * - `https://docupstoragecentcuspsto.blob.core.windows.net/`
 * - `https://docupstorageeasteu2psto.blob.core.windows.net/`
 * - `https://docupstorageeasteusdsto.blob.core.windows.net/` (Demo)
 * - `https://docupstoragejapajpepsto.blob.core.windows.net/`
 * - `https://docupstoragenortneupsto.blob.core.windows.net/`
 * - `https://docupstoragewestweupsto.blob.core.windows.net/`
 * - `https://docupstoragewestwu3dsto.blob.core.windows.net/` (Demo)
 *
 * **Secondary Storage Endpoints** (for redundancy/failover):
 * - `https://docupstorageaustauepsto-secondary.blob.core.windows.net/`
 * - `https://docupstoragecanacacpsto-secondary.blob.core.windows.net/`
 * - `https://docupstoragecentcuspsto-secondary.blob.core.windows.net/`
 * - `https://docupstorageeasteu2psto-secondary.blob.core.windows.net/`
 * - `https://docupstorageeasteusdsto-secondary.blob.core.windows.net/` (Demo)
 * - `https://docupstoragejapajpepsto-secondary.blob.core.windows.net/`
 * - `https://docupstoragenortneupsto-secondary.blob.core.windows.net/`
 * - `https://docupstoragewestweupsto-secondary.blob.core.windows.net/`
 * - `https://docupstoragewestwu3dsto-secondary.blob.core.windows.net/` (Demo)
 *
 * **Note**: You may whitelist all domains listed above, or contact your DocuSign administrator to determine which specific
 * region(s) your account uses to minimize the whitelist scope.
 *
 * **Supported File Formats & Content Types**:
 *
 * The table below shows common file formats and their recommended Content-Type headers.
 * **Note**: For the most up-to-date list of supported formats, headers, and constraints, always refer to the
 * `_action_templates` object in the API response, which provides dynamic configuration including:
 * - `allowed_formats`: Current list of supported file extensions
 * - `headers`: Required HTTP headers with examples
 * - `constraints`: Maximum file size and other limits
 * - `success_status_code`: Expected response code for successful uploads
 *
 * | Format | Extension | Content-Type |
 * |--------|-----------|--------------|
 * | PDF | .pdf | `application/pdf` |
 * | Word Document (2007+) | .docx | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
 * | Word Document (Legacy) | .doc | `application/msword` |
 * | PowerPoint Presentation (2007+) | .pptx | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
 * | PowerPoint Presentation (Legacy) | .ppt | `application/vnd.ms-powerpoint` |
 * | PowerPoint Slideshow | .ppsx | `application/vnd.openxmlformats-officedocument.presentationml.slideshow` |
 * | Excel Workbook (2007+) | .xlsx | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` |
 * | Excel Workbook (Legacy) | .xls | `application/vnd.ms-excel` |
 * | Excel Binary Workbook | .xlsb | `application/vnd.ms-excel.sheet.binary.macroenabled.12` |
 * | Rich Text Format | .rtf | `text/rtf` |
 * | WordPerfect Document | .wpd | `application/vnd.wordperfect` |
 * | HTML | .html, .htm | `text/html` |
 * | JPEG Image | .jpg, .jpeg | `image/jpeg` |
 * | PNG Image | .png | `image/png` |
 * | TIFF Image | .tif, .tiff | `image/tiff` |
 *
 * **Example Upload Requests**:
 *
 * PDF Document (with optional metadata):
 * ```
 * PUT https://storage.blob.core.windows.net/container/doc-id?signature=...
 * Content-Type: application/pdf
 * x-ms-blob-type: BlockBlob
 * x-ms-meta-filename: contract.pdf
 * x-ms-meta-metadata: "{\"provisions\":{\"jurisdiction\":\"California\"},\"custom_provisions\":{\"c_ClientId\":\"value\"}}"
 *
 * [Binary PDF data]
 * ```
 *
 * Word Document:
 * ```
 * PUT https://storage.blob.core.windows.net/container/doc-id?signature=...
 * Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
 * x-ms-blob-type: BlockBlob
 * x-ms-meta-filename: agreement.docx
 *
 * [Binary DOCX data]
 * ```
 *
 * Image:
 * ```
 * PUT https://storage.blob.core.windows.net/container/doc-id?signature=...
 * Content-Type: image/jpeg
 * x-ms-blob-type: BlockBlob
 * x-ms-meta-filename: signed-page.jpg
 *
 * [Binary JPEG data]
 * ```
 *
 * If set, this operation will use {@link Security.accessToken} from the global security.
 */
export function agreementManagerBulkJobCreateBulkUploadJob(
  client: IamClientCore,
  request: operations.CreateBulkUploadJobRequest,
  options?: RequestOptions,
): APIPromise<
  Result<
    components.BulkJob,
    | errors.ErrDetails
    | IamClientError
    | ResponseValidationError
    | ConnectionError
    | RequestAbortedError
    | RequestTimeoutError
    | InvalidRequestError
    | UnexpectedClientError
    | SDKValidationError
  >
> {
  return new APIPromise($do(
    client,
    request,
    options,
  ));
}

async function $do(
  client: IamClientCore,
  request: operations.CreateBulkUploadJobRequest,
  options?: RequestOptions,
): Promise<
  [
    Result<
      components.BulkJob,
      | errors.ErrDetails
      | IamClientError
      | ResponseValidationError
      | ConnectionError
      | RequestAbortedError
      | RequestTimeoutError
      | InvalidRequestError
      | UnexpectedClientError
      | SDKValidationError
    >,
    APICall,
  ]
> {
  const parsed = safeParse(
    request,
    (value) =>
      operations.CreateBulkUploadJobRequest$outboundSchema.parse(value),
    "Input validation failed",
  );
  if (!parsed.ok) {
    return [parsed, { status: "invalid" }];
  }
  const payload = parsed.value;
  const body = encodeJSON("body", payload.CreateBulkJob, { explode: true });

  const pathParams = {
    accountId: encodeSimple("accountId", payload.accountId, {
      explode: false,
      charEncoding: "percent",
    }),
  };
  const path = pathToFunc("/v1/accounts/{accountId}/upload/jobs")(pathParams);

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

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

  const context = {
    options: client._options,
    baseURL: options?.serverURL ?? client._baseURL ?? "",
    operationID: "createBulkUploadJob",
    oAuth2Scopes: null,

    resolvedSecurity: requestSecurity,

    securitySource: client._options.accessToken,
    retryConfig: options?.retries
      || client._options.retryConfig
      || {
        strategy: "backoff",
        backoff: {
          initialInterval: 500,
          maxInterval: 5000,
          exponent: 1.5,
          maxElapsedTime: 30000,
        },
        retryConnectionErrors: true,
      }
      || { strategy: "none" },
    retryCodes: options?.retryCodes || ["5XX", "429"],
  };

  const requestRes = client._createRequest(context, {
    security: requestSecurity,
    method: "POST",
    baseURL: options?.serverURL,
    path: path,
    headers: headers,
    body: body,
    userAgent: client._options.userAgent,
    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,
    isErrorStatusCode: (statusCode: number) =>
      matchStatusCode({ status: statusCode } as Response, ["4XX", "5XX"]),
    retryConfig: context.retryConfig,
    retryCodes: context.retryCodes,
  });
  if (!doResult.ok) {
    return [doResult, { status: "request-error", request: req }];
  }
  const response = doResult.value;

  const responseFields = {
    HttpMeta: { Response: response, Request: req },
  };

  const [result] = await M.match<
    components.BulkJob,
    | errors.ErrDetails
    | IamClientError
    | ResponseValidationError
    | ConnectionError
    | RequestAbortedError
    | RequestTimeoutError
    | InvalidRequestError
    | UnexpectedClientError
    | SDKValidationError
  >(
    M.json(200, components.BulkJob$inboundSchema),
    M.jsonErr([400, 403, 429], errors.ErrDetails$inboundSchema, {
      ctype: "application/problem+json",
    }),
    M.jsonErr(500, errors.ErrDetails$inboundSchema, {
      ctype: "application/problem+json",
    }),
    M.fail([401, "4XX"]),
    M.fail("5XX"),
  )(response, req, { extraFields: responseFields });
  if (!result.ok) {
    return [result, { status: "complete", request: req, response }];
  }

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