import { describe, it, expect } from 'vitest';
import { filterTagOptions } from './tag-picker-filter';
import type { ItemTag } from '@colectivo/types';

function tag(name: string, id = name): ItemTag {
	return {
		id,
		collective_id: 'c',
		name,
		color: 'slate',
		created_at: '2026-05-18T00:00:00Z'
	};
}

describe('filterTagOptions', () => {
	const all = [tag('Vegano'), tag('Oferta'), tag('Vegetariano'), tag('Bio')];

	it('TP-01: substring match is case-insensitive', () => {
		const result = filterTagOptions(all, 'veg', []);
		expect(result.matches.map((t) => t.name)).toEqual(['Vegano', 'Vegetariano']);
	});

	it('TP-02: returns the full list when query is empty', () => {
		const result = filterTagOptions(all, '', []);
		expect(result.matches).toHaveLength(4);
		expect(result.canCreate).toBe(false);
	});

	it('TP-03: canCreate is true when the query is non-empty and no exact match exists', () => {
		const result = filterTagOptions(all, 'Lácteo', []);
		expect(result.canCreate).toBe(true);
		expect(result.createName).toBe('Lácteo');
	});

	it('TP-04: canCreate is false when an exact (case-insensitive) match exists', () => {
		const result = filterTagOptions(all, 'vegano', []);
		expect(result.canCreate).toBe(false);
		// The exact match must still appear in the matches list.
		expect(result.matches.map((t) => t.name)).toContain('Vegano');
	});

	it('TP-05: excludes already-selected ids from the suggestions', () => {
		const result = filterTagOptions(all, 'veg', ['Vegano']);
		expect(result.matches.map((t) => t.name)).toEqual(['Vegetariano']);
	});

	it('TP-06: trims whitespace before evaluating the query', () => {
		const result = filterTagOptions(all, '   ', []);
		expect(result.matches).toHaveLength(4);
		expect(result.canCreate).toBe(false);
	});

	it('TP-07: createName preserves the user input verbatim (no lowercasing)', () => {
		const result = filterTagOptions(all, '  Sin-Gluten  ', []);
		expect(result.createName).toBe('Sin-Gluten');
		expect(result.canCreate).toBe(true);
	});
});
