import { DQRule, DQRuleTypes } from '../models/dq-rules.model'

/**
 * Rule types whose RULE_VALUE supplies the default value inserted into a cell
 * when a new row is added. Checked in priority order.
 */
const DEFAULT_VALUE_RULE_TYPES: DQRuleTypes[] = [
  'NOTNULL',
  'READONLY',
  'HIDDEN'
]

/**
 * Returns the default value for a column from DQ rules, used to pre-fill cells
 * when a new row is added. Looks for the first non-empty RULE_VALUE among
 * NOTNULL, READONLY and HIDDEN rules. Converts to number for numeric columns.
 *
 * @param colName column name to look up
 * @param dqRules array of DQ rules
 * @param colType column type (e.g., 'numeric', 'text')
 * @returns default value (string or number) if a default-providing rule exists
 *          with a non-empty value, otherwise undefined
 */
export function getColumnDefault(
  colName: string,
  dqRules: DQRule[],
  colType?: string
): string | number | undefined {
  const rule = dqRules.find(
    (rule: DQRule) =>
      rule.BASE_COL === colName &&
      DEFAULT_VALUE_RULE_TYPES.includes(rule.RULE_TYPE) &&
      rule.RULE_VALUE != null &&
      rule.RULE_VALUE.trim().length > 0
  )

  if (!rule) return undefined

  if (colType === 'numeric' && !isNaN(Number(rule.RULE_VALUE))) {
    return Number(rule.RULE_VALUE)
  }

  return rule.RULE_VALUE
}
