import {
  GetAvailabilityInputParams,
  GetSingleItemAvailabilityInputParams,
} from '../schemas';

/**
 * Converts single-item availability parameters to batch format.
 *
 * The batch availability method expects arrays of items, while the single-item
 * method accepts a single item. This converter transforms single → batch format
 * while preserving all parameters.
 *
 * Conversion rules by order type:
 * - InStore (Rücklage): item.itemId → itemsIds array
 * - Pickup (Abholung): item → items array
 * - Delivery/DIG/B2B/Download: item → items array
 *
 * @param params - Single item availability parameters
 * @returns Batch availability parameters compatible with getAvailabilities()
 *
 * @example
 * ```typescript
 * // InStore example
 * const single = { orderType: 'Rücklage', branchId: 42, itemId: 123 };
 * const batch = convertSingleItemToBatchParams(single);
 * // Returns: { orderType: 'Rücklage', branchId: 42, itemsIds: [123] }
 *
 * // Pickup example
 * const single = { orderType: 'Abholung', branchId: 42, item: { itemId: 123, ... } };
 * const batch = convertSingleItemToBatchParams(single);
 * // Returns: { orderType: 'Abholung', branchId: 42, items: [{ itemId: 123, ... }] }
 * ```
 */
export function convertSingleItemToBatchParams(
  params: GetSingleItemAvailabilityInputParams,
): GetAvailabilityInputParams {
  if (params.orderType === 'Rücklage') {
    // InStore: itemId → itemsIds array
    return {
      orderType: params.orderType,
      branchId: params.branchId,
      itemsIds: [params.itemId],
    };
  } else if (params.orderType === 'Abholung') {
    // Pickup: item → items array
    return {
      orderType: params.orderType,
      branchId: params.branchId,
      items: [params.item],
    };
  } else {
    // Delivery/DIG/B2B/Download: item → items array
    return {
      orderType: params.orderType,
      items: [params.item],
    } satisfies GetAvailabilityInputParams;
  }
}

/**
 * Extracts the itemId from single-item availability parameters.
 *
 * Different order types store the itemId in different places:
 * - InStore (Rücklage): directly in params.itemId
 * - All others: in params.item.itemId
 *
 * @param params - Single item availability parameters
 * @returns The itemId as a string for dictionary key lookup
 *
 * @example
 * ```typescript
 * // InStore
 * const itemId = extractItemIdFromSingleParams(
 *   { orderType: 'Rücklage', itemId: 123, ... }
 * ); // Returns: '123'
 *
 * // Other types
 * const itemId = extractItemIdFromSingleParams(
 *   { orderType: 'Versand', item: { itemId: 456 }, ... }
 * ); // Returns: '456'
 * ```
 */
export function extractItemIdFromSingleParams(
  params: GetSingleItemAvailabilityInputParams,
): string {
  const itemId =
    params.orderType === 'Rücklage' ? params.itemId : params.item.itemId;
  return String(itemId);
}
