import { OrderItemProcessingStatusValue } from '../../schemas';
import { ProcessingStatusState } from '../../models';

/**
 * Determines the completion status of order items based on their processing statuses.
 *
 * @param statuses - Array of processing status values to evaluate
 * @returns The processing status state:
 * - `ProcessingStatusState.Cancelled` if all items are cancelled
 * - `ProcessingStatusState.NotFound` if all items are marked as not available
 * - `ProcessingStatusState.Collected` if all items are collected
 * - `undefined` if statuses don't match any completion state
 *
 * @example
 * ```ts
 * const statuses = [512, 1024]; // StorniertKunde, Storniert
 * getProcessingStatusState(statuses); // ProcessingStatusState.Cancelled
 * ```
 */
export const getProcessingStatusState = (
  statuses: number[] | undefined,
): ProcessingStatusState | undefined => {
  if (!statuses || statuses.length === 0) {
    return undefined;
  }

  // Check if all statuses are ordered
  const allOrdered = statuses.every(
    (status) => status === OrderItemProcessingStatusValue.Bestellt,
  );
  if (allOrdered) {
    return ProcessingStatusState.Ordered;
  }

  // Check if all statuses are cancelled
  const allCancelled = statuses.every(
    (status) =>
      status === OrderItemProcessingStatusValue.StorniertKunde ||
      status === OrderItemProcessingStatusValue.Storniert ||
      status === OrderItemProcessingStatusValue.StorniertLieferant ||
      status === OrderItemProcessingStatusValue.AnsLagerNichtAbgeholt,
  );
  if (allCancelled) {
    return ProcessingStatusState.Cancelled;
  }

  // Check if all statuses are not available
  const allNotFound = statuses.every(
    (status) => status === OrderItemProcessingStatusValue.NichtLieferbar,
  );
  if (allNotFound) {
    return ProcessingStatusState.NotFound;
  }

  // Check if all statuses are collected
  const allCollected = statuses.every(
    (status) => status === OrderItemProcessingStatusValue.Abgeholt,
  );
  if (allCollected) {
    return ProcessingStatusState.Collected;
  }

  return undefined;
};
