import {
  buildCsvDownloadItem,
  buildPngDownloadItem,
  type DownloadItem,
} from '../actions/download'
import type { FormulaWidgetData } from './types'

export interface FormulaDownloadConfigArgs {
  filename: string
  getData: () => FormulaWidgetData
  /**
   * Optional getter for the widget's capture element (registered by
   * `Widget.State`). When provided, a PNG item is prepended.
   */
  getCaptureEl?: () => HTMLElement | null
  pngPixelRatio?: number
  pngBackgroundColor?: string | null
}

/**
 * Builds download items for the Formula widget. Always includes a CSV item
 * with one row per KPI (`prefix`, `value`, `suffix`, `note`, `delta`).
 * When `getCaptureEl` is supplied, prepends a PNG item that rasterises the
 * captured element via `html2canvas`.
 */
export function createFormulaDownloadConfig(
  args: FormulaDownloadConfigArgs,
): DownloadItem[] {
  const items: DownloadItem[] = []
  if (args.getCaptureEl) {
    items.push(
      buildPngDownloadItem({
        filename: args.filename,
        getCaptureEl: args.getCaptureEl,
        pixelRatio: args.pngPixelRatio,
        backgroundColor: args.pngBackgroundColor,
      }),
    )
  }
  items.push(
    buildCsvDownloadItem({
      filename: args.filename,
      getRows: () => {
        const data = args.getData()
        const rows: unknown[][] = [
          ['series', 'prefix', 'value', 'suffix', 'note', 'delta'],
        ]
        for (const d of data) {
          rows.push([
            d.series?.name ?? '',
            d.prefix ?? '',
            d.value,
            d.suffix ?? '',
            d.note ?? '',
            d.delta?.value ?? '',
          ])
        }
        return rows
      },
    }),
  )
  return items
}
