import { describe, expect, test } from 'bun:test';

import { decodeAttributedBody } from '@/shared/typedstream/decode';

/**
 * The backfill script's loop body is decode + UPDATE. The decode side is
 * already covered by shared/typedstream/__tests__/decode.test.ts. These
 * tests cover the slim glue: that a pg Buffer round-trips correctly through
 * Buffer.toString('base64') into decodeAttributedBody and yields the same
 * text the wire-path produces.
 */
describe('backfill-body-decoded glue', () => {
  test('Buffer.toString(base64) is equivalent to the wire-encoded string', () => {
    const marker = Buffer.from([0x4e, 0x53, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67]);
    const padding = Buffer.from([0x01, 0x95, 0x84, 0x01, 0x2b]);
    const payload = Buffer.from('backfilled text', 'utf-8');
    const length = Buffer.from([payload.length]);
    const blob = Buffer.concat([marker, padding, length, payload]);

    const wireBase64 = blob.toString('base64');
    const dbBuffer = blob;
    const dbBase64 = dbBuffer.toString('base64');

    expect(dbBase64).toBe(wireBase64);
    expect(decodeAttributedBody(dbBase64).text).toBe('backfilled text');
  });

  test('undecodable buffer leaves body_decoded null', () => {
    const garbage = Buffer.from([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]);
    const result = decodeAttributedBody(garbage.toString('base64'));
    expect(result.text).toBeNull();
  });
});
