import { KeyValueOfStringAndString } from '@isa/common/data-access';
import { CustomerFeatureKey, CustomerFeatureGroup } from '../schemas';

/**
 * Retrieves the first enabled customer feature that meets all validation criteria.
 *
 * A feature is considered valid if it satisfies ALL of the following conditions:
 * - `enabled` property must be `true`
 * - `description` property must exist and be non-empty
 * - `group` property must be 'd-customertype'
 *
 * When multiple valid features are found, the function prioritizes features in the following order:
 * 1. Features with key 'd-account' (highest priority)
 * 2. Features with key 'd-no-account' (second priority)
 * 3. The first valid feature in the array (fallback)
 *
 * @param customerFeatures - Array of customer feature objects to filter and evaluate
 * @returns The first enabled feature matching all criteria, or `undefined` if none are found
 *
 * @example
 * ```typescript
 * const features = [
 *   { key: 'b2b', enabled: true, description: 'B2B', group: 'd-customertype' },
 *   { key: 'd-account', enabled: true, description: 'Account', group: 'd-customertype' }
 * ];
 * const result = getEnabledCustomerFeature(features);
 * // Returns the 'd-account' feature (prioritized over 'b2b')
 * ```
 */
export const getEnabledCustomerFeature = (
  customerFeatures: KeyValueOfStringAndString[],
): KeyValueOfStringAndString | undefined => {
  const enabledFeatures = customerFeatures?.filter(
    (f) =>
      f?.enabled &&
      !!f?.description &&
      f?.group === CustomerFeatureGroup.DCustomerType,
  );

  // If multiple features are enabled, prefer 'd-account' or 'd-no-account'
  if (enabledFeatures?.length > 1) {
    const preferredFeature = enabledFeatures.find(
      (f) =>
        f.key === CustomerFeatureKey.DAccount ||
        f.key === CustomerFeatureKey.DNoAccount,
    );
    // If a preferred feature is found, return it; otherwise fall back to the first enabled feature
    return preferredFeature ?? enabledFeatures[0];
  }

  // Return the first enabled feature if only one is enabled
  return enabledFeatures?.[0];
};
