/**
 * @file signature.ts - API wrapper for IWS5 signature objects and functions.
 */

import { FetchError } from '../utils/fetchHelper.ts';
import { getAccessToken } from '../services/authService.ts';

/** Base URL for the IWS5 signature API endpoint */
export const SIGNATURE_API_URL =
  window.__APP_CONFIG__?.IWS5_API_URL + '/api/Signature';

/**
 * Response returned by the IWS5 API after a batch signing operation.
 * Indicates which work items were successfully signed and which were skipped (e.g., due to being locked or having no documents).
 */
export type SignatureResponse = {
  /** IDs of work items that were successfully signed */
  signedWorkItems: number[];

  /** IDs of work items that were skipped during the signing operation */
  skippedWorkItems: number[];
};

/**
 * Signs a list of work items.
 *
 * @param workItemIds IDs of work items to sign
 * @param fileBytes Uint8Array of digital certificate file bytes
 * @param password Password for digital certificate
 * @param issuer Issuer name of digital certificate
 * @throws FetchError If response is not 200-class
 */
export async function signWorkItemList(
  workItemIds: number[],
  fileBytes: number[],
  password: string,
  issuer: string
): Promise<SignatureResponse> {
  const _url = SIGNATURE_API_URL + '/sign-workitem-list';

  // Attempt POST /api/Signature/sign-workitem-list
  try {
    const response = await fetch(_url.toString(), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getAccessToken()}`,
      },
      body: JSON.stringify({
        workItemIds,
        fileBytes,
        password,
        issuer,
      }),
    });
    if (!response.ok) {
      const errorText = await response.text();
      throw new FetchError(errorText || 'Failed to sign work items', response);
    }

    return (await response.json()) as SignatureResponse;
  } catch (error) {
    throw new FetchError((error as Error).message);
  }
}
