import { parseCsv, unparseCsv } from './parseCsv';
/**
 * Rewrites a CSV so its header row matches the destination field keys and the
 * columns the user chose to skip are dropped.
 *
 * The data-hub import maps columns to fields strictly by `header == field-key`
 * (there is no server-side column mapping), so the chosen mapping has to be
 * applied to the file itself before upload — see plan O1.
 *
 * `resolvedMapping` maps each *original* CSV header to its destination field
 * key, or `null`/absent to skip that column — exactly what
 * `ImportState._resolveFieldMapping` produces. Columns are kept in their
 * original order (order is irrelevant to the server, which maps by header name,
 * but it keeps the output readable).
 *
 * NOTE: this reads the whole file into memory. For very large files a streaming
 * rewrite (papaparse `step`) would avoid that — deferred until it's a problem.
 */
export function rewriteCsvForImport(content, resolvedMapping) {
    const parsed = parseCsv(content);
    if ('code' in parsed) {
        throw new Error('Failed to parse CSV for import rewrite');
    }
    return rewriteParsedCsvForImport(parsed.headers, parsed.rows, resolvedMapping);
}
/**
 * Same rewrite as {@link rewriteCsvForImport} but from already-parsed rows —
 * used by `ImportState`, which holds the parsed CSV in memory and doesn't need
 * to re-parse.
 */
export function rewriteParsedCsvForImport(headers, rows, resolvedMapping) {
    const kept = headers
        .map((header, index) => ({ index, key: resolvedMapping[header] }))
        .filter((col) => col.key != null);
    const newHeaders = kept.map((col) => col.key);
    const newRows = rows.map((row) => kept.map((col) => row[col.index] ?? ''));
    return unparseCsv(newHeaders, newRows);
}
//# sourceMappingURL=rewriteCsv.js.map