import { Operator } from '@aurorajs.dev/core-common';
import { toSequelizeWhereKey } from './nested-column';

/**
 * Builds a Sequelize-compatible `where` clause for searching across
 * multiple columns using `iLike`. Produces an `[or]` array so any
 * matching column satisfies the filter.
 *
 * Column ids using dot notation (e.g. `'boundedContext.name'`) are translated
 * to Sequelize's `$assoc.col$` syntax automatically. The list query must
 * `include` the corresponding association — derive it via
 * `getRelationIncludes(columns)`.
 *
 * @param value - The search string
 * @param columns - Column ids to search in
 * @returns A where object for QueryStatement, or undefined if value is empty
 *
 * @example
 * buildSearchWhere('tag', ['name'])
 * // { '[or]': [{ name: { '[iLike]': '%tag%' } }] }
 *
 * buildSearchWhere('iam', ['name', 'boundedContext.name'])
 * // { '[or]': [
 * //   { name: { '[iLike]': '%iam%' } },
 * //   { '$boundedContext.name$': { '[iLike]': '%iam%' } },
 * // ] }
 */
export function buildSearchWhere(
  value: string,
  columns: string[],
): Record<string, unknown> | undefined {
  const trimmed = value?.trim();
  if (!trimmed || columns.length === 0) return undefined;

  return {
    [Operator.or]: columns.map((col) => ({
      [toSequelizeWhereKey(col)]: { [Operator.iLike]: `%${trimmed}%` },
    })),
  };
}
