jest.mock('@mongodb-js/zstd', () => ({
  decompress: jest.fn(),
}));

import { decompress } from '@mongodb-js/zstd';
import { tryDecompressToString, hasZstdMagic } from '../../../../../src/modules/netaclaw/runtime/weixin_db/zstd_decode.js';

const mockedDecompress = decompress as jest.MockedFunction<typeof decompress>;

describe('hasZstdMagic', () => {
  it('returns true when buf starts with 28 b5 2f fd', () => {
    expect(hasZstdMagic(Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x00]))).toBe(true);
  });
  it('returns false for plain bytes', () => {
    expect(hasZstdMagic(Buffer.from('hello', 'utf8'))).toBe(false);
  });
  it('returns false for too-short buffer', () => {
    expect(hasZstdMagic(Buffer.from([0x28, 0xb5, 0x2f]))).toBe(false);
  });
});

describe('tryDecompressToString', () => {
  it('decompresses zstd bytes with magic to UTF-8', async () => {
    const original = '你好 WCDB 群消息';
    const compressed = Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x00]);
    mockedDecompress.mockResolvedValueOnce(Buffer.from(original, 'utf8'));
    const result = await tryDecompressToString(compressed);
    expect(result).toBe(original);
    expect(mockedDecompress).toHaveBeenCalledWith(compressed);
  });

  it('passes through plain UTF-8 bytes without magic', async () => {
    const buf = Buffer.from('plain text', 'utf8');
    await expect(tryDecompressToString(buf)).resolves.toBe('plain text');
  });

  it('returns empty string for null/empty input', async () => {
    await expect(tryDecompressToString(null)).resolves.toBe('');
    await expect(tryDecompressToString(undefined)).resolves.toBe('');
    await expect(tryDecompressToString(Buffer.alloc(0))).resolves.toBe('');
  });
});
