/**
 * @file trackingRecord.ts - API wrapper for IWS5 tracking record objects and functions.
 */

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

/** Base URL for the IWS5 tracking records API endpoint */
export const TRACKING_RECORDS_API_URL =
  window.__APP_CONFIG__?.IWS5_API_URL + '/api/TrackingRecord';

/**
 * Represents a tracking record for a work item, as returned by the IWS5 API.
 * Each record captures a specific event that occurred during the work item's processing.
 */
export type TrackingRecord = {
  /** Unique identifier of the tracking record */
  id: number;

  /** ISO date string of when the tracking event occurred */
  trackingDate: string;

  /** ID of the work item this tracking record belongs to */
  workItemId: number;

  /** Numeric identifier of the event where tracking occurred */
  eventId: number;

  /** Username of the user who triggered the event; null if system-generated */
  userName: string | null;

  /** Description of the last action taken; null if not applicable */
  lastAction: string | null;

  /** User-provided or system-generated message associated with the event */
  message: string;

  /** Human-readable description of the tracking event */
  description: string;
};

/**
 * Retrieves the list of tracking records for a given work item.
 *
 * @param workItemId ID of work item to retrieve tracking records for
 * @returns List of tracking records
 * @throws FetchError If response is not 200-class
 */
export async function listTrackingRecords(
  workItemId: number
): Promise<TrackingRecord[]> {
  const _url = TRACKING_RECORDS_API_URL + '/' + workItemId;

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

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