import { Operator } from '@aurorajs.dev/core-common';
import { buildSearchWhere } from './build-search-where';

describe('buildSearchWhere', () => {
  it('returns undefined when value is empty', () => {
    expect(buildSearchWhere('', ['name'])).toBeUndefined();
  });

  it('returns undefined when value is whitespace only', () => {
    expect(buildSearchWhere('   ', ['name'])).toBeUndefined();
  });

  it('returns undefined when columns is empty', () => {
    expect(buildSearchWhere('foo', [])).toBeUndefined();
  });

  it('builds an [or] iLike clause for a flat column', () => {
    expect(buildSearchWhere('tag', ['name'])).toEqual({
      [Operator.or]: [{ name: { [Operator.iLike]: '%tag%' } }],
    });
  });

  it('combines multiple flat columns under [or]', () => {
    expect(buildSearchWhere('iam', ['name', 'code'])).toEqual({
      [Operator.or]: [
        { name: { [Operator.iLike]: '%iam%' } },
        { code: { [Operator.iLike]: '%iam%' } },
      ],
    });
  });

  it('wraps dotted column ids in $...$ for relation columns', () => {
    expect(buildSearchWhere('iam', ['name', 'boundedContext.name'])).toEqual({
      [Operator.or]: [
        { name: { [Operator.iLike]: '%iam%' } },
        { '$boundedContext.name$': { [Operator.iLike]: '%iam%' } },
      ],
    });
  });

  it('does not double-wrap a column id already in $...$ form', () => {
    expect(buildSearchWhere('iam', ['$boundedContext.name$'])).toEqual({
      [Operator.or]: [{ '$boundedContext.name$': { [Operator.iLike]: '%iam%' } }],
    });
  });

  it('trims the search value before wrapping in %...%', () => {
    expect(buildSearchWhere('  tag  ', ['name'])).toEqual({
      [Operator.or]: [{ name: { [Operator.iLike]: '%tag%' } }],
    });
  });
});
