/**
 * Filter operator utilities.
 *
 * Operators are loaded dynamically from capabilities.
 * Free plugin provides base operators, Pro plugin extends them.
 */

import { TriggerFieldType } from '../types/trigger';
import { FilterOperator, OperatorsByType } from '../types/filter';

/**
 * Default (free) operator labels - used as fallback if capabilities not loaded.
 */
const DEFAULT_OPERATORS: Record<string, string> = {
  equals: 'Equals',
  not_equals: 'Does not equal',
  contains: 'Contains',
  not_contains: 'Does not contain',
  greater_than: 'Greater than',
  less_than: 'Less than',
  is_empty: 'Is empty',
  is_not_empty: 'Is not empty',
};

/**
 * Default operators by field type.
 */
const DEFAULT_OPERATORS_BY_TYPE: OperatorsByType = {
  string: ['equals', 'not_equals', 'contains', 'not_contains', 'is_empty', 'is_not_empty'],
  integer: ['equals', 'not_equals', 'greater_than', 'less_than', 'is_empty', 'is_not_empty'],
  boolean: ['equals', 'is_empty', 'is_not_empty'],
  datetime: ['equals', 'not_equals', 'greater_than', 'less_than', 'is_empty', 'is_not_empty'],
  array: ['contains', 'not_contains', 'is_empty', 'is_not_empty'],
};

/**
 * Default operators that require a value input.
 */
const DEFAULT_OPERATORS_REQUIRING_VALUE: string[] = [
  'equals',
  'not_equals',
  'contains',
  'not_contains',
  'greater_than',
  'less_than',
];

/**
 * Get operator labels from capabilities or fallback to defaults.
 */
function getOperatorLabels(): Record<string, string> {
  return window.sequensyAPI?.capabilities?.filter_operators?.operators ?? DEFAULT_OPERATORS;
}

/**
 * Get operators by type from capabilities or fallback.
 */
function getOperatorsByType(): OperatorsByType {
  return (
    (window.sequensyAPI?.capabilities?.filter_operators?.operators_by_type as OperatorsByType) ??
    DEFAULT_OPERATORS_BY_TYPE
  );
}

/**
 * Get operators requiring value from capabilities or fallback.
 */
function getOperatorsRequiringValue(): string[] {
  return (
    window.sequensyAPI?.capabilities?.filter_operators?.operators_requiring_value ??
    DEFAULT_OPERATORS_REQUIRING_VALUE
  );
}

/**
 * Get valid operators for a given field type.
 */
export function getOperatorsForType(fieldType: TriggerFieldType): FilterOperator[] {
  const operatorsByType = getOperatorsByType();
  return operatorsByType[fieldType] || operatorsByType.string;
}

/**
 * Check if an operator requires a value input.
 */
export function operatorRequiresValue(operator: FilterOperator): boolean {
  return getOperatorsRequiringValue().includes(operator);
}

/**
 * Get the human-readable label for an operator.
 */
export function getOperatorLabel(operator: FilterOperator): string {
  const labels = getOperatorLabels();
  return labels[operator] || operator;
}
