package latencylog

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	"omnisocketgo/cmd/internal/protocol"
)

func TestWriteSummariesHTMLChart(t *testing.T) {
	aProcessing := int64(20_000_000)
	aQueue := int64(10_000_000)
	transport := int64(40_000_000)
	bProcessing := int64(30_000_000)
	endToEnd := int64(100_000_000)

	summaries := []Summary{
		{
			MessageType:                           protocol.MessageTypeText,
			MessageID:                             7,
			From:                                  "peer-a",
			To:                                    "peer-b",
			BodySize:                              5,
			AProcessingLatencyNS:                  &aProcessing,
			AQueueLatencyNS:                       &aQueue,
			ABTransportPropagationBQueueLatencyNS: &transport,
			BProcessingLatencyNS:                  &bProcessing,
			EndToEndLatencyNS:                     &endToEnd,
		},
		{
			MessageType:       protocol.MessageTypeFile,
			MessageID:         8,
			From:              "peer-b",
			To:                "peer-a",
			FileName:          "payload.bin",
			BodySize:          128,
			MissingTimestamps: []string{EventBRXSoftware},
		},
	}

	path := filepath.Join(t.TempDir(), "charts", "latency-summary.html")
	if err := WriteSummariesHTMLChart(path, summaries); err != nil {
		t.Fatalf("WriteSummariesHTMLChart() error = %v", err)
	}

	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("os.ReadFile() error = %v", err)
	}

	content := string(data)
	for _, want := range []string{
		"Latency Summary",
		"text #7",
		"peer-a -&gt; peer-b | 5 bytes",
		"End-to-end: 100.000 ms",
		"A processing 20.000 ms",
		"file #8 (payload.bin)",
		"Missing timestamps: B_RX_SOFTWARE",
	} {
		if !strings.Contains(content, want) {
			t.Fatalf("chart content missing %q\n%s", want, content)
		}
	}
}
