/**
 * Report renderers — scheduled-reports (wave-15).
 *
 * renderToFile(data, format) → { filename, contentType, body: ArrayBuffer }
 * Supports xlsx and pdf formats.
 */
import type { ReportData } from './report-generators/index'
import {
  sanitizeCell,
  newRtlWorksheet,
  writeFinancialWorkbook,
  applyHebrewFont,
} from './financial-export'

export interface RenderedFile {
  filename: string
  contentType: string
  body: ArrayBuffer
}

/**
 * Render report data to an xlsx file.
 */
async function renderXlsx(data: ReportData): Promise<RenderedFile> {
  const safeTitle = data.title.replace(/[^\w\s-]/g, '').trim().replace(/\s+/g, '_')
  const filename = `${safeTitle}_${data.period.from}_${data.period.to}.xlsx`

  const bytes = await writeFinancialWorkbook((wb) => {
    for (const section of data.sections) {
      const ws = newRtlWorksheet(wb, section.heading.slice(0, 31))

      // Header row
      const headerRow = ws.addRow(section.columns.map((c) => sanitizeCell(c)))
      headerRow.eachCell((cell) => {
        applyHebrewFont(cell)
        cell.font = { ...cell.font, bold: true }
      })

      // Data rows
      for (const row of section.rows) {
        const dataRow = ws.addRow(row.map((v) => sanitizeCell(v)))
        dataRow.eachCell((cell) => applyHebrewFont(cell))
      }

      // Auto-fit columns
      ws.columns.forEach((col) => {
        col.width = 20
      })
    }
  })

  return {
    filename,
    contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    body: bytes.buffer as ArrayBuffer,
  }
}

/**
 * Render report data to a file in the requested format.
 * Only xlsx is supported; pdf is not available for scheduled delivery.
 */
export async function renderToFile(
  data: ReportData,
  _format: 'xlsx',
): Promise<RenderedFile> {
  return renderXlsx(data)
}
