import { describe, it, expect } from 'vitest';
import { getNodeDescendants, isNodeCollapsed } from '../core/group-store';

describe('group-store utils', () => {
	describe('getNodeDescendants', () => {
		it('returns direct children', () => {
			const graph = {
				forEachNode: (cb: (id: string, attrs: { parentId?: string }) => void) => {
					cb('child1', { parentId: 'group1' });
					cb('child2', { parentId: 'group1' });
					cb('other', {});
				},
			};
			const desc = getNodeDescendants(graph, 'group1');
			expect(desc).toContain('child1');
			expect(desc).toContain('child2');
			expect(desc).not.toContain('other');
		});

		it('returns nested descendants', () => {
			const graph = {
				forEachNode: (cb: (id: string, attrs: { parentId?: string }) => void) => {
					cb('child1', { parentId: 'group1' });
					cb('grandchild', { parentId: 'child1' });
					cb('other', {});
				},
			};
			const desc = getNodeDescendants(graph, 'group1');
			expect(desc).toContain('child1');
			expect(desc).toContain('grandchild');
		});

		it('returns empty for non-group', () => {
			const graph = {
				forEachNode: (cb: (id: string, attrs: { parentId?: string }) => void) => {
					cb('n1', {});
					cb('n2', {});
				},
			};
			expect(getNodeDescendants(graph, 'n1')).toEqual([]);
		});
	});

	describe('isNodeCollapsed', () => {
		it('returns false for node with no ancestor collapsed', () => {
			const getParentId = (_id: string) => undefined;
			expect(isNodeCollapsed('n1', getParentId, new Set())).toBe(false);
		});

		it('returns true for node inside a collapsed group', () => {
			const getParentId = (id: string) => id === 'child' ? 'group1' : undefined;
			expect(isNodeCollapsed('child', getParentId, new Set(['group1']))).toBe(true);
		});

		it('returns true for nested child under collapsed ancestor', () => {
			const getParentId = (id: string) => {
				if (id === 'grandchild') return 'child';
				if (id === 'child') return 'group1';
				return undefined;
			};
			expect(isNodeCollapsed('grandchild', getParentId, new Set(['group1']))).toBe(true);
		});

		it('returns false for node whose parent is expanded', () => {
			const getParentId = (id: string) => id === 'child' ? 'group1' : undefined;
			expect(isNodeCollapsed('child', getParentId, new Set())).toBe(false);
		});
	});
});
