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

import { getAccessToken } from '../services/authService.ts';
import { FetchError } from '../utils/fetchHelper.ts';
import { StatusCodes } from 'http-status-codes';

/** Base URL for the IWS5 queues API endpoint */
export const QUEUES_API_URL =
  window.__APP_CONFIG__?.IWS5_API_URL + '/api/Queue';

/**
 * Represents a queue within a workflow process, as returned by the IWS5 API.
 * Work items reside in queues and are forwarded using buttons between events during processing.
 */
export type Queue = {
  /** Unique identifier of the queue */
  queueId: number;

  /** Internal name of the queue */
  queueName?: string;

  /** Optional display alias shown in the UI instead of queueName */
  queueAlias?: string;

  /** Whether work items in this queue support LPNU-specific digital signage */
  signable: boolean;
};

/**
 * Retrieves the list of queues for a given process.
 *
 * @param processId ID of process to retrieve queues for
 * @returns List of queues
 * @throws FetchError If response is not 200-class
 */
export async function listQueues(processId: number): Promise<Queue[]> {
  const _url = QUEUES_API_URL + '/' + processId;

  // Attempt GET /api/Queue/{processId}
  try {
    const response = await fetch(_url.toString(), {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getAccessToken()}`,
      },
    });
    if (!response.ok) {
      const errorText = await response.text();
      throw new FetchError(errorText || 'Failed to retrieve queues', response);
    }
    if (response.status === StatusCodes.NO_CONTENT) {
      return [] as Queue[];
    }

    return (await response.json()).queues as Queue[];
  } catch (error) {
    throw new FetchError((error as Error).message);
  }
}
