import { saveAs } from 'file-saver';
import json2csv, { parse } from 'json2csv';

/**
 * Generates a CSV file from JSON data and triggers a download in the client
 *
 * @param data json2csv data, see https://www.npmjs.com/package/json2csv#javascript-module-examples
 * @param fileName name of the downloaded file
 * @param opts json2csv options, see https://www.npmjs.com/package/json2csv#available-options
 */
export const downloadCsvFile = <T>(
  data: Readonly<T> | ReadonlyArray<T>,
  fileName: string,
  opts?: json2csv.Options<T>
) => {
  const csvOutput = parse(data, opts);

  const blob = new Blob([csvOutput], { type: 'text/csv' });
  const formattedFilename = fileName.endsWith('.csv')
    ? fileName
    : `${fileName}.csv`;

  saveAs(blob, formattedFilename);
};
