# frozen_string_literal: true

require "yaml"

module Reportgen
  # CSV export of a report's underlying data. Column headers are resolved
  # through the legacy alias mapping in config/schema.yml so that older
  # client integrations built against pre-2024 header names keep working.
  #
  # NOTE: this predates ExportWriter and still does its own inline row
  # writing below rather than delegating to it. The two were never merged.
  class Exporter
    SCHEMA_PATH = File.expand_path("../../config/schema.yml", __dir__)

    def export(records:)
      schema = YAML.safe_load(File.read(SCHEMA_PATH))
      columns = schema.fetch("columns")
      aliases = schema.fetch("legacy_aliases", {})

      headers = columns.map { |col| aliases.key(col) || col }

      lines = [headers.join(",")]
      records.each do |record|
        lines << columns.map { |col| record.fetch(col.to_sym, "").to_s }.join(",")
      end
      lines.join("\n")
    end
  end
end
