import { describe, it, expect } from 'vitest';
import { parseAttrParam, formatAttrParam, parseFacetQuery } from './attribute-filter';

describe('parseAttrParam', () => {
  it('returns key-only for input without colon', () => {
    expect(parseAttrParam('order')).toEqual({ key: 'order' });
  });

  it('splits on first colon, trims key, preserves value as-is', () => {
    expect(parseAttrParam('order:47')).toEqual({ key: 'order', value: '47' });
  });

  it('treats a value containing colons as a single value', () => {
    expect(parseAttrParam('trace-id:abc:123')).toEqual({ key: 'trace-id', value: 'abc:123' });
  });

  it('returns null for blank input', () => {
    expect(parseAttrParam('')).toBeNull();
    expect(parseAttrParam('   ')).toBeNull();
  });

  it('returns null for missing key', () => {
    expect(parseAttrParam(':x')).toBeNull();
  });

  it('returns null when the key contains invalid characters', () => {
    expect(parseAttrParam('bad key:1')).toBeNull();
  });
});

describe('formatAttrParam', () => {
  it('returns bare key for key-only filter', () => {
    expect(formatAttrParam({ key: 'order' })).toBe('order');
  });

  it('joins with colon when value is present', () => {
    expect(formatAttrParam({ key: 'order', value: '47' })).toBe('order:47');
  });

  it('joins with colon when value is empty string', () => {
    expect(formatAttrParam({ key: 'order', value: '' })).toBe('order:');
  });
});

describe('parseFacetQuery', () => {
  it('matches `key: value`', () => {
    expect(parseFacetQuery('order: 47')).toEqual({ key: 'order', value: '47' });
  });

  it('matches `key:value` without spaces', () => {
    expect(parseFacetQuery('order:47')).toEqual({ key: 'order', value: '47' });
  });

  it('matches wildcard values', () => {
    expect(parseFacetQuery('order: 4*')).toEqual({ key: 'order', value: '4*' });
  });

  it('returns null when the key contains invalid characters', () => {
    expect(parseFacetQuery('bad key: 1')).toBeNull();
  });

  it('returns null without a colon', () => {
    expect(parseFacetQuery('order')).toBeNull();
  });

  it('returns null with an empty value side', () => {
    expect(parseFacetQuery('order:   ')).toBeNull();
  });
});
