// Sequelize helper functions: literal(), fn(), col()
// Used sparingly in Payment Kit (~7 places)

export function literal(sql: string) {
  return { __literal: true, sql };
}

export function fn(name: string, ...args: any[]) {
  return { __fn: true, name, args };
}

export function col(name: string) {
  return { __col: true, name };
}

// Convert helpers to SQL string
export function helperToSQL(value: any): string {
  if (!value || typeof value !== 'object') return String(value);
  if (value.__literal) return value.sql;
  if (value.__col) {
    // Handle dotted col names
    if (value.name.includes('.')) return `"${value.name.replace('.', '"."')}"`;
    return `"${value.name}"`;
  }
  if (value.__fn) {
    const args = value.args.map((a: any) => {
      if (a === null || a === undefined) return 'NULL';
      if (typeof a === 'string') {
        // String args in fn() are usually column names (e.g., fn('COUNT', col('id')))
        // But literal strings passed to fn should be quoted differently
        // Convention: use col() for column refs; bare strings are treated as column names too
        return `"${a}"`;
      }
      if (typeof a === 'number') return String(a);
      return helperToSQL(a);
    });
    return `${value.name}(${args.join(', ')})`;
  }
  // Sequelize.where() wrapper
  if (value.__sequelizeWhere) {
    const lhsSQL = helperToSQL(value.lhs);
    const rhsSQL = value.rhs === null ? 'NULL' : '?';
    return `${lhsSQL} = ${rhsSQL}`;
  }
  return String(value);
}
