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

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

/** Base URL for the IWS5 buttons API endpoint */
export const BUTTONS_API_URL =
  window.__APP_CONFIG__?.IWS5_API_URL + '/api/Buttons';

/**
 * Represents a queue-level action button returned by the IWS5 API.
 * Each button corresponds to a workflow action the user may perform to direct a work item through a process.
 */
export type Button = {
  /** Display name of the button shown in the UI */
  name: string;

  /** Internal action value sent to the backend when the button is clicked */
  value: string;

  /** Whether the current user has permission to click this button */
  allowedToClick: boolean;

  /** Positional index used for ordering buttons in the UI */
  index: number;
};

/**
 * Retrieves the list of buttons for a given queue (or inbox).
 *
 * @param queueId ID of queue
 * @param workItemReferenceId WorkItemReferenceId of work item (for inboxes)
 * @returns List of buttons
 * @throws FetchError If response is not 200-class
 */
export async function listButtons(
  queueId: number,
  workItemReferenceId?: number
): Promise<Button[]> {
  const _url = assembleQueryParams(BUTTONS_API_URL, {
    queueId,
    workItemReferenceId,
  });

  // Attempt GET /api/Buttons
  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 buttons', response);
    }
    if (response.status === StatusCodes.NO_CONTENT) {
      return [] as Button[];
    }

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