/**
 * CSV generation utilities for board reports.
 */

/**
 * Escape a CSV field value.
 * Wraps in quotes if the value contains commas, quotes, or newlines.
 */
export function escapeCSVField(value: unknown): string {
	if (value === null || value === undefined) return '';
	const str = String(value);
	if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
		return '"' + str.replace(/"/g, '""') + '"';
	}
	return str;
}

/**
 * Convert an array of objects to CSV string.
 */
export function arrayToCSV(
	data: Record<string, unknown>[],
	columns: { key: string; header: string }[]
): string {
	const header = columns.map((c) => escapeCSVField(c.header)).join(',');
	const rows = data.map((row) => columns.map((c) => escapeCSVField(row[c.key])).join(','));
	return '\ufeff' + header + '\n' + rows.join('\n');
}

/**
 * Create a CSV Response with proper headers for browser download.
 */
export function csvResponse(csvContent: string, filename: string): Response {
	return new Response(csvContent, {
		headers: {
			'Content-Type': 'text/csv; charset=utf-8',
			'Content-Disposition': `attachment; filename="${filename}"`
		}
	});
}
