// Pure CSV builder for cycle measurement exports.
//
// Produces a semicolon-separated CSV with a German header line. Fields that
// start with =, +, -, or @ are prefixed with an apostrophe to prevent
// spreadsheet formula injection (OWASP CSV-injection protection).

const INJECTION_LEAD = /^[=+\-@]/

function sanitizeField(value: string): string {
  if (INJECTION_LEAD.test(value)) return `'${value}`
  return value
}

function escapeField(value: string | number | null | undefined): string {
  if (value === null || value === undefined) return ''
  const str = String(value)
  return sanitizeField(str)
}

export interface CycleCsvRow {
  station: string
  cycle: number
  ct: number
  timeType: string | null
}

/**
 * Build a semicolon-delimited CSV string from cycle measurement rows.
 * Header: Station;Zyklus;Zeit;Zeitart
 */
export function buildCycleCsv(rows: CycleCsvRow[]): string {
  const header = 'Station;Zyklus;Zeit;Zeitart'
  if (rows.length === 0) return header
  const dataLines = rows.map(
    (r) =>
      [
        escapeField(r.station),
        escapeField(r.cycle),
        escapeField(r.ct),
        escapeField(r.timeType),
      ].join(';')
  )
  return [header, ...dataLines].join('\n')
}

/**
 * Trigger a browser download of a CSV string.
 * fileName should NOT include the .csv extension — it is appended here.
 */
export function downloadCsv(csvContent: string, fileName: string): void {
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${fileName}.csv`
  a.click()
  URL.revokeObjectURL(url)
}
