/**
 * Typed row extraction from `db.execute()` results.
 *
 * Neon-http with poolQueryViaFetch returns `{ rows: T[] }`; some drivers return
 * a bare array. Callers must use these helpers so `.rows` never escapes a module
 * without a known row type.
 */

export type ExecuteResult<T> = T[] | { rows: T[] };

/**
 * Normalize execute output to a typed row array.
 *
 * Accepts `unknown` because `db.execute<T>()` on a `Querier` (the abstract
 * `PgQueryResultHKT` union) resolves to `unknown` — this helper is the single
 * documented cast chokepoint. Callers pass the row type explicitly: `executeRows<Row>(result)`.
 */
export function executeRows<T>(result: unknown): T[] {
  if (Array.isArray(result)) return result as T[];
  return (result as { rows?: T[] }).rows ?? [];
}

/** First row from execute output, or undefined when empty. */
export function firstExecuteRow<T>(result: unknown): T | undefined {
  return executeRows<T>(result)[0];
}
