import { describe, it, expect } from 'vitest';
import { parseCapture } from '../capture-fetch.js';

describe('parseCapture', () => {
  it('trims response body when total exceeds 256KB cap', () => {
    const largeBody = 'y'.repeat(300_000);
    const capture = parseCapture({
      request_headers: { 'Content-Type': 'application/json' },
      response_headers: {},
      request_body: Buffer.from('x'.repeat(100_000)).toString('base64'),
      response_body: Buffer.from(largeBody).toString('base64'),
      timestamp: '2024-01-01T00:00:00Z',
      model: 'test-model',
      duration_ms: 100,
    }, 'host1', 1);

    expect(capture.responseBody).toContain('[truncated: capture exceeds 256KB cap]');
    const totalBytes = Buffer.byteLength(capture.requestBody + capture.responseBody);
    expect(totalBytes).toBeLessThanOrEqual(256 * 1024 + 100);
  });

  it('does not trim when under cap', () => {
    const capture = parseCapture({
      request_headers: {},
      response_headers: {},
      request_body: Buffer.from('small request').toString('base64'),
      response_body: Buffer.from('small response').toString('base64'),
      timestamp: '2024-01-01T00:00:00Z',
      model: 'test-model',
      duration_ms: 50,
    }, 'host1', 2);

    expect(capture.requestBody).toBe('small request');
    expect(capture.responseBody).toBe('small response');
    expect(capture.responseBody).not.toContain('[truncated');
  });

  it('handles missing base64 bodies gracefully', () => {
    const capture = parseCapture({
      timestamp: '2024-01-01T00:00:00Z',
    }, 'host1', 3);

    expect(capture.requestBody).toBe('');
    expect(capture.responseBody).toBe('');
  });

  it('decodes base64 (invalid base64 produces binary, not raw string)', () => {
    // Buffer.from(str, 'base64') does not throw on invalid base64 —
    // it decodes what it can. The catch block only triggers on actual
    // Buffer.from exceptions, which are rare.
    const capture = parseCapture({
      request_body: Buffer.from('valid json').toString('base64'),
      response_body: Buffer.from('{"result": true}').toString('base64'),
      timestamp: '2024-01-01T00:00:00Z',
    }, 'host1', 4);

    expect(capture.requestBody).toBe('valid json');
    expect(capture.responseBody).toBe('{"result": true}');
  });
});
