import { Utils } from './Utils.js';
/** Represents a raw SQL fragment with optional parameters, usable as both a value and an object key via Symbol coercion. */
export class RawQueryFragment {
  sql;
  params;
  static #rawQueryReferences = new WeakMap();
  #key;
  constructor(sql, params = []) {
    this.sql = sql;
    this.params = params;
  }
  /** Returns a unique symbol key for this fragment, creating and caching it on first access. */
  get key() {
    if (!this.#key) {
      this.#key = Symbol(this.toJSON());
      RawQueryFragment.#rawQueryReferences.set(this.#key, this);
    }
    return this.#key;
  }
  /** Creates a new fragment with an alias appended via `as ??`. */
  as(alias) {
    return new RawQueryFragment(`${this.sql} as ??`, [...this.params, alias]);
  }
  [Symbol.toPrimitive](hint) {
    // if a fragment is converted to string (used as an object key), return a unique symbol
    // and save a weak reference to map so we can retrieve it when compiling the query
    if (hint === 'string') {
      return this.key;
    }
    throw new Error(`Trying to modify raw SQL fragment: '${this.sql}'`);
  }
  get [Symbol.toStringTag]() {
    return this.toJSON();
  }
  toJSON() {
    return `raw('${this.sql}')`;
  }
  clone() {
    return this;
  }
  /** Checks whether the given value is a symbol that maps to a known raw query fragment. */
  static isKnownFragmentSymbol(key) {
    return typeof key === 'symbol' && this.#rawQueryReferences.has(key);
  }
  /** Checks whether an object has any symbol keys that are known raw query fragments. */
  static hasObjectFragments(object) {
    return (
      Utils.isPlainObject(object) &&
      Object.getOwnPropertySymbols(object).some(symbol => this.isKnownFragmentSymbol(symbol))
    );
  }
  /** Checks whether the given value is a RawQueryFragment instance or a known fragment symbol. */
  static isKnownFragment(key) {
    if (key instanceof RawQueryFragment) {
      return true;
    }
    return this.isKnownFragmentSymbol(key);
  }
  /** Retrieves the RawQueryFragment associated with the given key (instance or symbol). */
  static getKnownFragment(key) {
    if (key instanceof RawQueryFragment) {
      return key;
    }
    if (typeof key !== 'symbol') {
      return;
    }
    return this.#rawQueryReferences.get(key);
  }
  /** @ignore */
  /* v8 ignore next */
  [Symbol.for('nodejs.util.inspect.custom')]() {
    if (this.params) {
      return { sql: this.sql, params: this.params };
    }
    return { sql: this.sql };
  }
}
export { RawQueryFragment as Raw };
Object.defineProperties(RawQueryFragment.prototype, {
  __raw: { value: true, enumerable: false },
});
/** Checks whether the given value is a `RawQueryFragment` instance. */
export function isRaw(value) {
  return typeof value === 'object' && value !== null && '__raw' in value;
}
/** @internal */
export const ALIAS_REPLACEMENT = '[::alias::]';
/** @internal */
export const ALIAS_REPLACEMENT_RE = '\\[::alias::\\]';
/**
 * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
 * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
 * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
 * This adds a runtime safety to the raw query fragments.
 *
 * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
 *
 * ```ts
 * // as a value
 * await em.find(User, { time: raw('now()') });
 *
 * // as a key
 * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
 *
 * // value can be empty array
 * await em.find(User, { [raw('(select 1 = 1)')]: [] });
 * ```
 *
 * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
 *
 * ```ts
 * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
 * ```
 *
 * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
 *
 * ```ts
 * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
 * ```
 *
 * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
 *
 * ```ts
 * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
 * ```
 *
 * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
 *
 * ```ts
 * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
 * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
 * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
 * @Entity({ schema: 'library' })
 * export class Author { ... }
 * ```
 *
 * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
 *
 * ```ts
 * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
 * @Entity({ schema: 'library' })
 * export class Author { ... }
 * ```
 */
export function raw(sql, params) {
  if (sql instanceof RawQueryFragment) {
    return sql;
  }
  if (sql instanceof Function) {
    sql = sql(ALIAS_REPLACEMENT);
  }
  if (sql === '??' && Array.isArray(params)) {
    return new RawQueryFragment(sql, params);
  }
  if (Array.isArray(sql)) {
    // for composite FK we return just a simple string
    return Utils.getPrimaryKeyHash(sql);
  }
  if (typeof params === 'object' && !Array.isArray(params)) {
    const pairs = Object.entries(params);
    const objectParams = [];
    for (const [key, value] of pairs) {
      sql = sql.replace(`:${key}:`, '??');
      sql = sql.replace(`:${key}`, '?');
      objectParams.push(value);
    }
    return new RawQueryFragment(sql, objectParams);
  }
  return new RawQueryFragment(sql, params);
}
/**
 * Alternative to the `raw()` helper allowing to use it as a tagged template function for the simple cases.
 *
 * ```ts
 * // as a value
 * await em.find(User, { time: sql`now()` });
 *
 * // as a key
 * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
 *
 * // value can be empty array
 * await em.find(User, { [sql`(select 1 = 1)`]: [] });
 *
 * // with type parameter for assignment without casting
 * entity.date = sql<Date>`now()`;
 * ```
 */
export function sql(sql, ...values) {
  return raw(sql.join('?'), values);
}
/** Creates a raw SQL function expression wrapping the given key (e.g., `lower(name)`). */
export function createSqlFunction(func, key) {
  if (typeof key === 'string') {
    return raw(`${func}(${key})`);
  }
  return raw(a => `${func}(${key(a)})`);
}
sql.ref = (...keys) => raw('??', [keys.join('.')]);
sql.now = length => raw('current_timestamp' + (length == null ? '' : `(${length})`));
sql.lower = key => createSqlFunction('lower', key);
sql.upper = key => createSqlFunction('upper', key);
/**
 * Tag function providing quoting of db identifiers (table name, columns names, index names, ...).
 *
 * Within the template literal on which the tag function is applied, all placeholders are considered to be database identifiers, and will thus be quoted as so according to the database in use.
 *
 * ```ts
 * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("name")
 * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`name`)
 * @Index({ name: 'custom_idx_on_name', expression: (table, columns, indexName) => quote`create index ${indexName} on ${table} (${columns.name})` })
 * @Entity({ schema: 'library' })
 * export class Author { ... }
 * ```
 */
export function quote(expParts, ...values) {
  return raw(expParts.join('??'), values);
}
