(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(["exports", "./util", "./expr"], factory);
  } else if (typeof exports !== "undefined") {
    factory(exports, require("./util"), require("./expr"));
  } else {
    var mod = {
      exports: {}
    };
    factory(mod.exports, global.util, global.expr);
    global.limit = mod.exports;
  }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _util, _expr) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.limitToSQL = limitToSQL;
  function composePrefixValSuffix(stmt) {
    if (!stmt) return [];
    return [stmt.prefix.map(_util.literalToSQL).join(' '), (0, _expr.exprToSQL)(stmt.value), stmt.suffix.map(_util.literalToSQL).join(' ')];
  }
  function fetchOffsetToSQL(stmt) {
    const {
      fetch,
      offset
    } = stmt;
    const result = [...composePrefixValSuffix(offset), ...composePrefixValSuffix(fetch)];
    return result.filter(_util.hasVal).join(' ');
  }
  function limitOffsetToSQL(limit) {
    const {
      seperator,
      value
    } = limit;
    if (!value) {
      // Handle simple numeric limit object from ClickHouse
      if (limit && (limit.type === 'number' || limit.value != null)) {
        return (0, _util.connector)('LIMIT', (0, _expr.exprToSQL)(limit));
      }
      return '';
    }
    if (value.length === 1 && seperator === 'offset') return (0, _util.connector)('OFFSET', (0, _expr.exprToSQL)(value[0]));
    return (0, _util.connector)('LIMIT', value.map(_expr.exprToSQL).join(`${seperator === 'offset' ? ' ' : ''}${(0, _util.toUpper)(seperator)} `));
  }
  function limitToSQL(limit) {
    if (!limit) return '';
    // Handle array format from ClickHouse parser
    if (Array.isArray(limit)) {
      if (limit.length === 1) {
        const limitExpr = limit[0];
        // Handle nested value structure
        if (limitExpr && limitExpr.value) {
          return (0, _util.connector)('LIMIT', (0, _expr.exprToSQL)(limitExpr.value));
        }
        return (0, _util.connector)('LIMIT', (0, _expr.exprToSQL)(limitExpr));
      }
      if (limit.length === 2) {
        const offsetExpr = limit[0];
        const limitExpr = limit[1];
        const offsetVal = offsetExpr && offsetExpr.value ? offsetExpr.value : offsetExpr;
        const limitVal = limitExpr && limitExpr.value ? limitExpr.value : limitExpr;
        return `${(0, _util.connector)('LIMIT', (0, _expr.exprToSQL)(limitVal))} ${(0, _util.connector)('OFFSET', (0, _expr.exprToSQL)(offsetVal))}`;
      }
      return '';
    }
    if (limit.fetch || limit.offset) return fetchOffsetToSQL(limit);
    return limitOffsetToSQL(limit);
  }
});