import { RemissionItemType, RemissionListType } from '../models';
import { RemissionItem } from '../stores';
import { isReturnItem, isReturnSuggestion } from '../guards';

/**
 * Determines the concrete type of a RemissionItem
 * @param item - The item to check
 * @param remissionListType - Optional fallback to determine type when guards are ambiguous
 * @returns The type as a RemissionItemType enum value
 */
export const getItemType = (
  item: RemissionItem,
  remissionListType?: RemissionListType,
): RemissionItemType => {
  const isReturnItemType = isReturnItem(item);
  const isReturnSuggestionItemType = isReturnSuggestion(item);

  // If exactly one guard matches, use it directly (without remissionListType)
  if (isReturnItemType && !isReturnSuggestionItemType) {
    return RemissionItemType.ReturnItem;
  }

  if (isReturnSuggestionItemType && !isReturnItemType) {
    return RemissionItemType.ReturnSuggestion;
  }

  // If both are true or both are false, use remissionListType as fallback
  if (remissionListType) {
    // Pflichtremission typically contains ReturnItems
    // Abteilungsremission typically contains ReturnSuggestions
    if (remissionListType === 'Pflichtremission') {
      return RemissionItemType.ReturnItem;
    }

    if (remissionListType === 'Abteilungsremission') {
      return RemissionItemType.ReturnSuggestion;
    }
  }

  // If no remissionListType provided or unrecognized, return Unknown
  return RemissionItemType.Unknown;
};
