import { describe, expect, test } from 'bun:test';
import { parseWorkspaceKey } from './workspace-identity';
import { terminalStateKey } from '../../apps/Terminal/state-key';

describe('parseWorkspaceKey', () => {
  test('reads a dashboard key', () => {
    expect(parseWorkspaceKey('ws-layout-agent-mvp')).toEqual({
      kind: 'dashboard',
      id: 'agent-mvp',
      key: 'ws-layout-agent-mvp',
    });
  });

  test('reads a screen key', () => {
    expect(parseWorkspaceKey('screens/email')).toEqual({ kind: 'screen', id: 'email', key: 'screens/email' });
  });

  // Both halves may contain dashes and slashes; only the first prefix is structural.
  test('keeps the whole remainder as the id', () => {
    expect(parseWorkspaceKey('ws-layout-my-dash-2')?.id).toBe('my-dash-2');
    expect(parseWorkspaceKey('screens/soulseek-v2')?.id).toBe('soulseek-v2');
  });

  test('is null for anything that is neither', () => {
    expect(parseWorkspaceKey(null)).toBeNull();
    expect(parseWorkspaceKey(undefined)).toBeNull();
    expect(parseWorkspaceKey('')).toBeNull();
    expect(parseWorkspaceKey('email')).toBeNull();
    // The prefixes alone name nothing.
    expect(parseWorkspaceKey('ws-layout-')).toBeNull();
    expect(parseWorkspaceKey('screens/')).toBeNull();
  });
});

describe('terminalStateKey', () => {
  // The regression this rule exists for: a wrapper that passed the raw key through produced
  // `ws-host-terminals-ws-layout-my-dash`, which the server parsed back out as a dashboard id and created.
  test('strips the layout prefix rather than nesting it', () => {
    const key = terminalStateKey('host-terminals', parseWorkspaceKey('ws-layout-my-dash'));
    expect(key).toBe('ws-host-terminals-my-dash');
    expect(key).not.toContain('ws-layout');
  });

  test('screens and unknown workspaces share the defaults row', () => {
    expect(terminalStateKey('terminals', parseWorkspaceKey('screens/chat'))).toBe('ws-terminals-default');
    expect(terminalStateKey('terminals', null)).toBe('ws-terminals-default');
  });

  test('carries the panel-state prefixes the dispatcher allow-lists', () => {
    const dashboard = parseWorkspaceKey('ws-layout-d1');
    expect(terminalStateKey('tmux', dashboard)).toBe('ws-tmux-d1');
    expect(terminalStateKey('nvim', dashboard)).toBe('ws-nvim-d1');
    expect(terminalStateKey('claude-code', dashboard)).toBe('ws-claude-code-d1');
  });
});
