import { describe, it, expect } from 'vitest';
import { parseInteractiveBrowseWaitingHuman } from './interactive-browse-result.js';

// Codex follow-up #4: the parser cast `sessionId` to string without checking it
// is present and actually a string, so malformed waiting_human output could
// produce a typed waiting-human result carrying `browserSessionId: undefined`.
describe('parseInteractiveBrowseWaitingHuman — sessionId validation (Codex #4)', () => {
  const valid = JSON.stringify({ action: 'waiting_human', waitReason: 'login', sessionId: 'abc123' });

  it('returns null for a non-InteractiveBrowse tool', () => {
    expect(parseInteractiveBrowseWaitingHuman('Read', valid)).toBeNull();
  });

  it('returns null when sessionId is missing', () => {
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', JSON.stringify({ action: 'waiting_human', waitReason: 'login' }))).toBeNull();
  });

  it('returns null when sessionId is not a string', () => {
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', JSON.stringify({ action: 'waiting_human', waitReason: 'login', sessionId: 123 }))).toBeNull();
  });

  it('returns null when sessionId is an empty string', () => {
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', JSON.stringify({ action: 'waiting_human', waitReason: 'login', sessionId: '' }))).toBeNull();
  });

  it('returns null for a valid InteractiveBrowse result whose action is not waiting_human', () => {
    // The common case: a normal browse completion must NOT be parked.
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', JSON.stringify({ action: 'done', sessionId: 'abc123' }))).toBeNull();
  });

  it('returns null when waitReason is missing or non-string', () => {
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', JSON.stringify({ action: 'waiting_human', sessionId: 'abc123' }))).toBeNull();
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', JSON.stringify({ action: 'waiting_human', waitReason: 5, sessionId: 'abc123' }))).toBeNull();
  });

  it('returns null for non-JSON output', () => {
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', 'not json')).toBeNull();
  });

  it('returns the payload when action, waitReason, and sessionId are all valid', () => {
    expect(parseInteractiveBrowseWaitingHuman('InteractiveBrowse', valid)).toEqual({ waitReason: 'login', sessionId: 'abc123' });
  });
});
