lib/forage/export/export_excel.ex

defmodule Forage.Export.ExportExcel do
  alias Forage.Export.ExportCommon
  alias Forage.Export.ExportedTable
  alias Elixlsx.{Workbook, Sheet}

  def to_sheet(name, schema, associations, entities) do
    {header, normal_rows} =
      ExportCommon.entities_to_header_and_rows(
        schema,
        associations,
        entities
      )

    pretty_header =
      for cell <- header do
        [to_string(cell), bold: true]
      end

    rows = [pretty_header | normal_rows]

    %Sheet{
      name: name,
      rows: rows
    }
  end

  def to_tmp_file(data) do
    path = ExportCommon.tmp_file_path(".xlsx")
    to_file(path, data)

    path
  end

  def to_file(path, data) do
    workbook =
      Enum.reduce(data, %Workbook{}, fn table, workbook ->
        %ExportedTable{
          name: name,
          schema: schema,
          assocs: associations,
          entries: entries} = table

        sheet = to_sheet(name, schema, associations, entries)
        Workbook.append_sheet(workbook, sheet)
      end)

    Elixlsx.write_to(workbook, path)
  end
end