/**
 * JSONB read helpers.
 *
 * porsager/postgres returns `jsonb` columns already parsed into JS values (an
 * object/array), NOT a JSON string. Calling JSON.parse on that throws
 * ("[object Object] is not valid JSON"). These helpers accept either shape so a
 * read works whether the driver parsed the column or handed back a string.
 */

/** Coerce a JSONB column value to a string array. */
export function jsonbStringArray(value: unknown): string[] {
  let v = value;
  if (typeof v === 'string') {
    try { v = JSON.parse(v); } catch { return []; }
  }
  return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
}

/** Coerce a JSONB column value to an array (elements untyped). */
export function jsonbArray(value: unknown): unknown[] {
  let v = value;
  if (typeof v === 'string') {
    try { v = JSON.parse(v); } catch { return []; }
  }
  return Array.isArray(v) ? v : [];
}

/** Coerce a JSONB column value to a number array. */
export function jsonbNumberArray(value: unknown): number[] {
  return jsonbArray(value).filter((x): x is number => typeof x === 'number');
}

/** Coerce a JSONB column value to a plain object, or null. */
export function jsonbObject(value: unknown): Record<string, unknown> | null {
  let v = value;
  if (v == null) return null;
  if (typeof v === 'string') {
    try { v = JSON.parse(v); } catch { return null; }
  }
  return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
}
