import { PassThrough } from 'stream';
import csv from 'csv-parser';

/** Parses an uploaded CSV buffer into typed bulk-import rows. */
export function parseCsvRows<Row>(fileBuffer: Buffer): Promise<Row[]> {
  const bufferStream = new PassThrough();
  const results: Row[] = [];
  bufferStream.end(Buffer.from(fileBuffer));

  return new Promise((resolve, reject) => {
    bufferStream
      .pipe(csv())
      .on('data', (row: Row) => results.push(row))
      .on('end', () => resolve(results))
      .on('error', reject);
  });
}
