import {
  CustomerTypeAnalysis,
  OrderOptionsAnalysis,
  ShoppingCartItem,
} from '../models';
import { EntityContainer } from '@isa/common/data-access';

/**
 * Analyzes shopping cart items to determine which order types are present.
 *
 * @remarks
 * Pure function that examines the orderType feature of each item to identify:
 * - Take away orders (Rücklage)
 * - Pick up orders (Abholung)
 * - Download orders
 * - Standard delivery (Versand)
 * - Digital delivery (DIG-Versand)
 * - B2B delivery (B2B-Versand)
 *
 * Used during checkout completion to determine payment requirements and
 * destination update needs.
 *
 * @param items - Shopping cart items to analyze
 * @returns Analysis result with boolean flags for each order type and unwrapped items
 *
 * @example
 * ```typescript
 * const items = [
 *   { data: { features: { orderType: 'Versand' } } },
 *   { data: { features: { orderType: 'Abholung' } } }
 * ];
 * const analysis = analyzeOrderOptions(items);
 * // { hasDelivery: true, hasPickUp: true, hasTakeAway: false, ... }
 * ```
 */
export function analyzeOrderOptions(
  items: EntityContainer<ShoppingCartItem>[],
): OrderOptionsAnalysis {
  return {
    hasTakeAway: items.some(
      (item) => item.data?.features?.['orderType'] === 'Rücklage',
    ),
    hasPickUp: items.some(
      (item) => item.data?.features?.['orderType'] === 'Abholung',
    ),
    hasDownload: items.some(
      (item) => item.data?.features?.['orderType'] === 'Download',
    ),
    hasDelivery: items.some(
      (item) => item.data?.features?.['orderType'] === 'Versand',
    ),
    hasDigDelivery: items.some(
      (item) => item.data?.features?.['orderType'] === 'DIG-Versand',
    ),
    hasB2BDelivery: items.some(
      (item) => item.data?.features?.['orderType'] === 'B2B-Versand',
    ),
    items: items.map((d) => d.data as ShoppingCartItem),
  };
}

/**
 * Analyzes customer features to determine customer type characteristics.
 *
 * @remarks
 * Pure function that converts feature flags into typed boolean properties:
 * - isOnline: webshop customer
 * - isGuest: guest account
 * - isB2B: business customer
 * - hasCustomerCard: loyalty card holder (Pay4More)
 * - isStaff: employee/staff member
 *
 * Used during checkout to determine payment requirements and payer necessity.
 *
 * @param features - Customer feature flags (e.g., { webshop: 'webshop', b2b: 'b2b' })
 * @returns Analysis result with boolean flags for each customer type
 *
 * @example
 * ```typescript
 * const features = { webshop: 'webshop', p4mUser: 'p4mUser' };
 * const analysis = analyzeCustomerTypes(features);
 * // { isOnline: true, hasCustomerCard: true, isB2B: false, ... }
 * ```
 */
export function analyzeCustomerTypes(
  features: Record<string, string>,
): CustomerTypeAnalysis {
  return {
    isOnline: !!features?.['webshop'],
    isGuest: !!features?.['guest'],
    isB2B: !!features?.['b2b'],
    hasCustomerCard: !!features?.['p4mUser'],
    isStaff: !!features?.['staff'],
  };
}
