package documents

import (
	"path/filepath"
	"slices"
	"testing"
	"time"

	"github.com/shopspring/decimal"
	"github.com/tech/sendico/billing/documents/internal/content"
	"github.com/tech/sendico/billing/documents/renderer"
	"github.com/tech/sendico/billing/documents/storage/model"
)

func TestTemplateRenderer_Render(t *testing.T) {
	path := filepath.Join("..", "..", "..", "templates", "acceptance.tpl")

	tmpl, err := newTemplateRenderer(path)
	if err != nil {
		t.Fatalf("newTemplateRenderer: %v", err)
	}

	snapshot := model.ActSnapshot{
		PaymentID:        "PAY-001",
		Date:             time.Date(2026, 1, 30, 0, 0, 0, 0, time.UTC),
		ExecutorFullName: "Jane Doe",
		Amount:           decimal.RequireFromString("123.45"),
		Currency:         "USD",
	}

	blocks, err := tmpl.Render(snapshot)
	if err != nil {
		t.Fatalf("Render: %v", err)
	}

	if len(blocks) == 0 {
		t.Fatalf("expected blocks, got none")
	}

	title := findBlock(blocks, renderer.TagTitle)

	if title == nil {
		t.Fatalf("expected title block")
	}

	if !slices.Contains(title.Lines, content.AcceptanceTemplate.Title) {
		t.Fatalf("expected title content not found")
	}

	kv := findBlock(blocks, renderer.TagKV)
	if kv == nil {
		t.Fatalf("expected kv block")
	}

	foundExecutor := false

	for _, row := range kv.Rows {
		if len(row) >= 2 && row[0] == content.AcceptanceTemplate.PartyExecutorLabel && row[1] == snapshot.ExecutorFullName {
			foundExecutor = true

			break
		}
	}

	if !foundExecutor {
		t.Fatalf("expected executor name in kv block")
	}

	table := findBlock(blocks, renderer.TagTable)
	if table == nil {
		t.Fatalf("expected table block")
	}

	foundAmount := false

	for _, row := range table.Rows {
		if len(row) >= 2 && row[1] == "123.45 USD" {
			foundAmount = true

			break
		}
	}

	if !foundAmount {
		t.Fatalf("expected amount in table block")
	}
}

func findBlock(blocks []renderer.Block, tag renderer.Tag) *renderer.Block {
	for i := range blocks {
		if blocks[i].Tag == tag {
			return &blocks[i]
		}
	}

	return nil
}
