import { isRagFeatureNotAllowed, parseChatErrorPayload } from './chatErrors';

describe('parseChatErrorPayload', () => {
  it('parses an error-type websocket payload', () => {
    const raw = JSON.stringify({ type: 'error', code: 'feature_not_allowed', content: 'no rag' });
    expect(parseChatErrorPayload(raw)).toEqual({
      type: 'error',
      code: 'feature_not_allowed',
      content: 'no rag',
    });
  });

  it('returns null for non-error JSON payloads', () => {
    expect(parseChatErrorPayload(JSON.stringify({ type: 'text', content: 'hi' }))).toBeNull();
  });

  it('returns null for plain streamed text chunks', () => {
    expect(parseChatErrorPayload('just a plain chunk of text')).toBeNull();
  });
});

describe('isRagFeatureNotAllowed', () => {
  it('is false for unrelated error codes', () => {
    expect(isRagFeatureNotAllowed({ code: 'prompt_quota_exceeded', content: 'slow down' })).toBe(false);
  });

  it('is false when feature_not_allowed is about a different feature', () => {
    expect(
      isRagFeatureNotAllowed({
        code: 'feature_not_allowed',
        content: 'Your plan does not include image generation.',
        details: { feature: 'image_generation' },
      })
    ).toBe(false);
  });

  it('is true when details.feature mentions rag', () => {
    expect(
      isRagFeatureNotAllowed({
        code: 'feature_not_allowed',
        content: 'Blocked',
        details: { feature: 'rag' },
      })
    ).toBe(true);
  });

  it('is true when the message text mentions rag without structured details', () => {
    expect(
      isRagFeatureNotAllowed({
        code: 'feature_not_allowed',
        content: 'Your plan does not include RAG document search.',
      })
    ).toBe(true);
  });

  it('is false for a null/undefined payload', () => {
    expect(isRagFeatureNotAllowed(null)).toBe(false);
    expect(isRagFeatureNotAllowed(undefined)).toBe(false);
  });
});
