import type { PickFirstNonzeroOp } from '../transforms.schema';
import type { Row } from '../row';

/**
 * pick_first_nonzero — 多个数值列里挑第一个 > 0 的,对应 label 写到 output_field。
 *
 * 例(payment 17 列推 channel):
 *   pay_wechat=100, pay_alipay=0, ... → output_field='wechat'
 *   都为 0 / null → output_field = default
 *
 * 数值识别:
 *   - number > 0 ✓
 *   - string 可 parse 为 number > 0 ✓
 *   - null / undefined / NaN / 0 / 负数 → 不命中
 */
export function runPickFirstNonzero(op: PickFirstNonzeroOp, rows: Row[]): Row[] {
  return rows.map((row) => {
    const next: Row = { ...row };
    let picked = op.default;
    for (const cand of op.candidates) {
      if (isPositiveNumber(row[cand.column])) {
        picked = cand.value;
        break;
      }
    }
    next[op.output_field] = picked;
    return next;
  });
}

function isPositiveNumber(v: unknown): boolean {
  if (typeof v === 'number') return Number.isFinite(v) && v > 0;
  if (typeof v === 'string') {
    const n = Number(v);
    return Number.isFinite(n) && n > 0;
  }
  return false;
}
