import { describe, expect, it } from 'vitest';
import { FilterValue, FilterValues } from '../../Filters';
import { filterToPostGraphileFilter } from './FilterTransformer';

const mockMap: { [key: string]: string } = {
  title: 'includesInsensitive',
};

describe('filterToPostGraphileFilter', () => {
  it('transforms simple filters to postgraphile filters', () => {
    const mockFilter: FilterValues<{ title: string }> = {
      title: 'Mocking Bird',
    };

    const titleFilter = filterToPostGraphileFilter<{ [key: string]: string }>(
      mockFilter,
      mockMap,
    );

    expect(titleFilter).toEqual({
      title: { [mockMap['title']]: mockFilter['title'] },
    });
  });

  it('transforms an array combination of a filter to postgraphile filters', () => {
    const mockFilter: FilterValues<{ tags: string }> = { tags: 'Mocking Bird' };

    const mockComplexMap = {
      tags: ['some', 'name', 'includes'],
    };

    const tagFilter = filterToPostGraphileFilter<{ [key: string]: string }>(
      mockFilter,
      mockComplexMap,
    );

    expect(tagFilter).toEqual({
      tags: { some: { name: { includes: mockFilter['tags'] } } },
    });
  });

  it('transforms a filter to postgraphile filter using a function', () => {
    const filterFunction = (value: FilterValue): Record<string, unknown> => {
      const values = String(value).split('|');
      return {
        greaterThan: values[0],
        lessThan: values[1],
      };
    };

    const greaterThan = '01:10:00';
    const lessThan = '01:30:00';

    const mockFilter: FilterValues<{ duration: string }> = {
      duration: `${greaterThan}|${lessThan}`,
    };

    const mockFuncFilterMap = {
      duration: filterFunction,
    };

    const tagFilter = filterToPostGraphileFilter<{ [key: string]: string }>(
      mockFilter,
      mockFuncFilterMap,
    );

    expect(tagFilter).toEqual({
      duration: { greaterThan, lessThan },
    });
  });

  it('returns undefined if an empty object is given', () => {
    const mockFilter: FilterValues<Record<string, unknown>> = {};

    const filter = filterToPostGraphileFilter<{ [key: string]: string }>(
      mockFilter,
      mockMap,
    );

    expect(filter).toBeUndefined();
  });
});
