import { describe, it, expect } from 'vitest';
import { toggleSpecialtyChild, toggleSpecialtyRoot, removeSpecialtyEntry, type ChildMap } from './specialtySelection';

// درخت نمونه: والد ۱۰ با فرزندهای ۱۱ و ۱۲؛ والد ۲۰ با فرزند ۲۱؛ ریشهٔ بی‌فرزند ۳۰.
const childMap: ChildMap = {
  10: [{ id: 11 }, { id: 12 }],
  20: [{ id: 21 }],
};

describe('toggleSpecialtyChild', () => {
  it('adds a child together with its parent', () => {
    expect(toggleSpecialtyChild([], 11, 10, childMap)).toEqual([10, 11]);
  });

  it('allows a second specialty from another group — the bug that was fixed', () => {
    expect(toggleSpecialtyChild([10, 11], 21, 20, childMap)).toEqual([10, 11, 20, 21]);
  });

  it('adds a sibling and keeps the shared parent', () => {
    expect(toggleSpecialtyChild([10, 11], 12, 10, childMap)).toEqual([10, 11, 12]);
  });

  it('removing one sibling keeps the parent while another sibling stays', () => {
    expect(toggleSpecialtyChild([10, 11, 12], 11, 10, childMap)).toEqual([10, 12]);
  });

  it('removing the last child of a group also drops the parent', () => {
    expect(toggleSpecialtyChild([10, 11], 11, 10, childMap)).toEqual([]);
  });

  it('never duplicates the parent id', () => {
    const out = toggleSpecialtyChild([10, 11], 12, 10, childMap);
    expect(out.filter(id => id === 10)).toHaveLength(1);
  });
});

describe('toggleSpecialtyRoot', () => {
  it('adds a childless root', () => {
    expect(toggleSpecialtyRoot([], 30)).toEqual([30]);
  });

  it('adds a root next to an existing selection', () => {
    expect(toggleSpecialtyRoot([10, 11], 30)).toEqual([10, 11, 30]);
  });

  it('toggles a root off without touching the rest', () => {
    expect(toggleSpecialtyRoot([10, 11, 30], 30)).toEqual([10, 11]);
  });
});

describe('removeSpecialtyEntry', () => {
  it('removes only the targeted child+parent, not the whole selection', () => {
    expect(removeSpecialtyEntry([10, 11, 20, 21], 11, 10, childMap)).toEqual([20, 21]);
  });

  it('keeps the parent when a sibling remains', () => {
    expect(removeSpecialtyEntry([10, 11, 12], 11, 10, childMap)).toEqual([10, 12]);
  });

  it('removes a childless root entry', () => {
    expect(removeSpecialtyEntry([10, 11, 30], 30, null, childMap)).toEqual([10, 11]);
  });
});
