import type { FilterOp, WhereRule } from '../transforms.schema';
import { isEmptyText, type Row } from '../row';

/**
 * filter — 按 where 规则保留行(等价 SQL WHERE 行级过滤)。
 *
 * where 是 AND 关系:所有字段规则都通过才保留。
 *
 * 规则:
 *   - not_empty: true   — 字段非 null/undefined/空字符串
 *   - in: [...]         — 字段值在列表中
 *   - equals: x         — 字段值等于 x
 */
export function runFilter(op: FilterOp, rows: Row[]): { rows: Row[]; dropped: number } {
  const out: Row[] = [];
  let dropped = 0;
  for (const row of rows) {
    if (passAll(row, op.where)) {
      out.push(row);
    } else {
      dropped++;
    }
  }
  return { rows: out, dropped };
}

function passAll(row: Row, where: Record<string, WhereRule>): boolean {
  for (const [field, rule] of Object.entries(where)) {
    const v = row[field];
    if ('not_empty' in rule) {
      if (isEmptyText(v)) return false;
    } else if ('in' in rule) {
      const set = new Set(rule.in.map((x) => String(x)));
      if (!set.has(String(v))) return false;
    } else if ('equals' in rule) {
      if (String(v) !== String(rule.equals)) return false;
    }
  }
  return true;
}
