import { describe, it, expect } from 'vitest';
import { jsonbStringArray, jsonbArray, jsonbNumberArray, jsonbObject } from '../jsonb.js';

describe('jsonbStringArray', () => {
  it('passes through an already-parsed array (porsager behavior)', () => {
    expect(jsonbStringArray(['a', 'b'])).toEqual(['a', 'b']);
  });
  it('parses a JSON string array', () => {
    expect(jsonbStringArray('["a","b"]')).toEqual(['a', 'b']);
  });
  it('filters non-strings out of a parsed array', () => {
    expect(jsonbStringArray(['a', 1, null, 'b'])).toEqual(['a', 'b']);
  });
  it('returns [] for null / invalid', () => {
    expect(jsonbStringArray(null)).toEqual([]);
    expect(jsonbStringArray('not json')).toEqual([]);
    expect(jsonbStringArray({})).toEqual([]);
  });
});

describe('jsonbArray', () => {
  it('passes through an already-parsed array of objects (eval tasks)', () => {
    expect(jsonbArray([{ id: 't1' }])).toEqual([{ id: 't1' }]);
  });
  it('parses a JSON string array', () => {
    expect(jsonbArray('[{"id":"t1"}]')).toEqual([{ id: 't1' }]);
  });
  it('returns [] for null / invalid / non-array', () => {
    expect(jsonbArray(null)).toEqual([]);
    expect(jsonbArray('nope')).toEqual([]);
    expect(jsonbArray({})).toEqual([]);
  });
});

describe('jsonbNumberArray', () => {
  it('passes through an already-parsed number array (bench token grids)', () => {
    expect(jsonbNumberArray([128, 512])).toEqual([128, 512]);
  });
  it('parses a JSON string array and filters non-numbers', () => {
    expect(jsonbNumberArray('[128,"x",512]')).toEqual([128, 512]);
  });
  it('returns [] for null / invalid', () => {
    expect(jsonbNumberArray(null)).toEqual([]);
    expect(jsonbNumberArray('nope')).toEqual([]);
  });
});

describe('jsonbObject', () => {
  it('passes through an already-parsed object', () => {
    expect(jsonbObject({ a: 1 })).toEqual({ a: 1 });
  });
  it('parses a JSON string object', () => {
    expect(jsonbObject('{"a":1}')).toEqual({ a: 1 });
  });
  it('returns null for arrays, null, and invalid', () => {
    expect(jsonbObject([1, 2])).toBeNull();
    expect(jsonbObject(null)).toBeNull();
    expect(jsonbObject('nope')).toBeNull();
  });
});
