import { describe, it, expect } from '#test';
import { addUrlParams, facetsToParams } from './url.ts';


let url: URL;

const paramsSuite = describe({
  name: 'addUrlParams()',
  beforeEach() {
    url = new URL('https://apptus.com/');
  }
});

it(paramsSuite, 'should remove null/undefined values', () => {
  addUrlParams(url, { sure: '1', nope: undefined, niet: null, yes: '2' });
  expect(url.href).toBe('https://apptus.com/?sure=1&yes=2');
});

it(paramsSuite, 'should convert primitives to strings', () => {
  addUrlParams(url, {
    name: 'John',
    age: 42,
    isWick: true
  });
  expect(url.href).toBe('https://apptus.com/?name=John&age=42&isWick=true');
});

it(paramsSuite, 'should join array values with "|"', () => {
  addUrlParams(url, {
    cart: ['pk1', 'pk2', 'pk3'],
    bools: [false, false, true],
    nums: [1, 2, 3, 9001]
  });
  const p = encodeURIComponent('|');
  expect(url.href).toBe(`https://apptus.com/?cart=pk1${p}pk2${p}pk3&bools=false${p}false${p}true&nums=1${p}2${p}3${p}9001`);
});


const facetSuite = describe('facetsToParams()');

it(facetSuite, 'should prefix all facets with `f.` in their parameter names', () => {
  const params = facetsToParams({ foo: ['a'], bar: ['b'] });
  expect(Object.keys(params)).toEqual(['f.foo', 'f.bar']);
});

it(facetSuite, 'should pass regular param values unchanged', () => {
  const items = ['one', 'two', 'three'];
  const params = facetsToParams({ items });
  expect(params['f.items']).toBe(items);
});

it(facetSuite, 'should convert min & max range values into multiple parameters', () => {
  expect(facetsToParams({ price: { min: 15, max: 32 } })).toEqual({ 'f.price.min': 15, 'f.price.max': 32 });
});

it(facetSuite, 'should convert min or max range values into a single parameter', () => {
  expect(facetsToParams({ price: { max: 99 } })).toEqual({ 'f.price.max': 99 });
  expect(facetsToParams({ coolness: { min: 9001 } })).toEqual({ 'f.coolness.min': 9001 });
});

it(facetSuite, 'should give the correct result for kitchen sink example', () => {
  const params = facetsToParams({ brand: ['nike', 'adidas'], price: { max: 500 } });
  expect(params).toEqual({ 'f.brand': ['nike', 'adidas'], 'f.price.max': 500 });
});
