import path from 'path';

import { describe, expect, it } from 'vitest';

import {
  groupKey,
  isValidGroupFolder,
  resolveGroupFolderPath,
  resolveGroupIpcPath,
} from './group-folder.js';

describe('group folder validation', () => {
  it('accepts normal group folder names', () => {
    expect(isValidGroupFolder('main')).toBe(true);
    expect(isValidGroupFolder('family-chat')).toBe(true);
    expect(isValidGroupFolder('Team_42')).toBe(true);
  });

  it('accepts composite tenant/folder names', () => {
    expect(isValidGroupFolder('default/general')).toBe(true);
    expect(isValidGroupFolder('tenant-1/project-x')).toBe(true);
    expect(isValidGroupFolder('Acme/Team_42')).toBe(true);
  });

  it('rejects invalid composite names', () => {
    expect(isValidGroupFolder('a/b/c')).toBe(false); // too many segments
    expect(isValidGroupFolder('/general')).toBe(false); // empty tenant
    expect(isValidGroupFolder('tenant/')).toBe(false); // empty folder
    expect(isValidGroupFolder('tenant/global')).toBe(false); // reserved folder
  });

  it('rejects traversal and reserved names', () => {
    expect(isValidGroupFolder('../../etc')).toBe(false);
    expect(isValidGroupFolder('/tmp')).toBe(false);
    expect(isValidGroupFolder('global')).toBe(false);
    expect(isValidGroupFolder('')).toBe(false);
  });

  it('groupKey creates composite from tenant + folder', () => {
    expect(groupKey('tenant1', 'general')).toBe('tenant1/general');
    expect(groupKey('tenant1', 'tenant1/general')).toBe('tenant1/general'); // already composite
  });

  it('resolves safe paths under groups directory', () => {
    const resolved = resolveGroupFolderPath('family-chat');
    expect(resolved.endsWith(`${path.sep}groups${path.sep}family-chat`)).toBe(
      true,
    );
  });

  it('resolves safe paths under data ipc directory', () => {
    const resolved = resolveGroupIpcPath('family-chat');
    expect(
      resolved.endsWith(`${path.sep}data${path.sep}ipc${path.sep}family-chat`),
    ).toBe(true);
  });

  it('throws for unsafe folder names', () => {
    expect(() => resolveGroupFolderPath('../../etc')).toThrow();
    expect(() => resolveGroupIpcPath('/tmp')).toThrow();
  });
});
