package webui

import (
	"strings"
	"testing"
)

// A summary row the user built in the editor must reach the PDF. Before, the caller
// had to restate it by hand — so a row someone created showed on screen and then
// quietly vanished from the export, which is the one number they most likely wanted
// in the file.
func TestPDFPicksUpTheTablesOwnSummaryRows(t *testing.T) {
	s := newCalcTable()
	s.AddSummaryRow(UserSummaryRow{
		ID: "total", Label: "Total revenue", Fn: CALC_FN_SUM,
		Operands: []string{"Revenue"}, DataType: CALC_TYPE_NUMBER, Precision: CalcPrecision(0),
	})
	s.Render()

	pdf := string(s.ExportPDFBytes(AutoTablePDFHeader{Title: "Report"}))
	if !strings.Contains(pdf, "Total revenue") {
		t.Error("the table's own summary row is missing from the PDF")
	}
	if !strings.Contains(pdf, "300") {
		t.Error("the summary row's VALUE is missing from the PDF (100 + 200)")
	}
}

// A calculated column the user built must reach it too, with its per-row values.
func TestPDFPicksUpCalculatedColumns(t *testing.T) {
	s := newCalcTable()
	s.AddCalculated(UserCalculatedColumn{
		ID: "total", DisplayName: "Row total", Fn: CALC_FN_SUM,
		Operands: []string{"Revenue", "Cost"}, DataType: CALC_TYPE_NUMBER, Precision: CalcPrecision(0),
	})
	s.Render()

	pdf := string(s.ExportPDFBytes(AutoTablePDFHeader{Title: "Report"}))
	if !strings.Contains(pdf, "Row total") {
		t.Error("the calculated column's header is missing from the PDF")
	}
	// Per row, not the column total: 100+40 and 200+50.
	for _, want := range []string{"140", "250"} {
		if !strings.Contains(pdf, want) {
			t.Errorf("calculated value %s missing from the PDF", want)
		}
	}
}

// An explicit Summaries list is an escape hatch and must win.
func TestPDFExplicitSummariesWin(t *testing.T) {
	s := newCalcTable()
	s.AddSummaryRow(UserSummaryRow{ID: "a", Label: "From the table", Fn: CALC_FN_SUM,
		Operands: []string{"Revenue"}})
	s.Render()

	pdf := string(s.ExportPDFBytes(AutoTablePDFHeader{
		Summaries: []AutoTablePDFSummary{{Label: "Caller supplied", Value: "42"}},
	}))
	if !strings.Contains(pdf, "Caller supplied") {
		t.Error("an explicit summary list was ignored")
	}
	if strings.Contains(pdf, "From the table") {
		t.Error("the table's rows were added on top of the caller's")
	}
}
