/**
 * Pure logic backing TagPicker.svelte — extracted so it can be unit-tested
 * without rendering a component.
 *
 * Given the collective's full tag list, a search query, and the set of
 * already-selected tag ids, returns:
 *   - `matches`: tags matching the query (substring, case-insensitive)
 *     with already-selected entries filtered out
 *   - `canCreate`: whether the "Create `query`" affordance should appear
 *     (true iff the trimmed query is non-empty AND no existing tag matches
 *     the query exactly, case-insensitive)
 *   - `createName`: the verbatim trimmed query — used as the new tag name
 *     when the user picks the create affordance (no casing applied)
 */
import type { ItemTag } from '@colectivo/types';

export interface TagFilterResult {
	matches: ItemTag[];
	canCreate: boolean;
	createName: string;
}

export function filterTagOptions(
	all: ItemTag[],
	query: string,
	selectedIds: string[]
): TagFilterResult {
	const trimmed = query.trim();
	const lowerQuery = trimmed.toLowerCase();
	const selectedSet = new Set(selectedIds);

	const filtered = all.filter((t) => !selectedSet.has(t.id));

	const matches = trimmed
		? filtered.filter((t) => t.name.toLowerCase().includes(lowerQuery))
		: filtered;

	const exactMatchExists = all.some((t) => t.name.toLowerCase() === lowerQuery);

	return {
		matches,
		canCreate: trimmed.length > 0 && !exactMatchExists,
		createName: trimmed
	};
}
