/**
 * Export data to CSV file
 */
interface CSVRow {
    [key: string]: string | number | null;
}

export function exportToCSV(
    headers: string[],
    rows: CSVRow[],
    filename: string,
): void {
    const csv = [
        headers.join(','),
        ...rows.map((row) =>
            headers
                .map((header) => {
                    const value = row[header];
                    return value !== null && value !== undefined
                        ? String(value)
                        : '';
                })
                .join(','),
        ),
    ].join('\n');

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
}

/**
 * Export data to CSV file with object-based rows (alternative format)
 */
export function exportToCSVWithObjects(rows: CSVRow[], filename: string): void {
    if (rows.length === 0) return;

    const headers = Object.keys(rows[0]);
    exportToCSV(headers, rows, filename);
}
