import { RemissionItem } from '../stores';

/**
 * Sorts the remission items in the response based on specific criteria:
 * - Items with impediments are moved to the end of the list.
 * - Within impediments, items are sorted by attempt count (ascending).
 * - Manually added items are prioritized to appear first.
 * - (Commented out) Items can be sorted by creation date in descending order.
 * @param {RemissionItem[]} items - The response object containing remission items to be sorted
 * @returns {void} The function modifies the response object in place
 */
export const orderByListItems = (items: RemissionItem[]): void => {
  items.sort((a, b) => {
    const aHasImpediment = !!a.impediment;
    const bHasImpediment = !!b.impediment;
    const aIsManuallyAdded = a.source === 'manually-added';
    const bIsManuallyAdded = b.source === 'manually-added';

    // First priority: move all items with impediment to the end of the list
    if (!aHasImpediment && bHasImpediment) {
      return -1;
    }
    if (aHasImpediment && !bHasImpediment) {
      return 1;
    }

    // If both have impediments, sort by attempts (ascending)
    if (aHasImpediment && bHasImpediment) {
      const aAttempts = a.impediment?.attempts ?? 0;
      const bAttempts = b.impediment?.attempts ?? 0;
      return aAttempts - bAttempts;
    }

    // Second priority: manually-added items come first
    if (aIsManuallyAdded && !bIsManuallyAdded) {
      return -1;
    }
    if (!aIsManuallyAdded && bIsManuallyAdded) {
      return 1;
    }

    return 0;
  });
};
