package office

import (
	"archive/zip"
	"bytes"
	"context"
	"strings"
	"testing"
)

func TestRenderReportValidDocx(t *testing.T) {
	data, err := NewRenderer().RenderReport(context.Background(), "测试报告 <X&Y>", []Section{
		{Heading: "第一章 背景", Body: "这是第一段。\n这是第二段，含特殊字符 < > &。"},
		{Heading: "第二章 分析", Body: "结论行。"},
	})
	if err != nil {
		t.Fatal(err)
	}
	zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
	if err != nil {
		t.Fatalf("not a valid zip: %v", err)
	}
	want := map[string]bool{"[Content_Types].xml": false, "_rels/.rels": false, "word/document.xml": false}
	var docXML string
	for _, f := range zr.File {
		if _, ok := want[f.Name]; ok {
			want[f.Name] = true
		}
		if f.Name == "word/document.xml" {
			rc, _ := f.Open()
			var b strings.Builder
			buf := make([]byte, 4096)
			for {
				n, e := rc.Read(buf)
				b.Write(buf[:n])
				if e != nil {
					break
				}
			}
			rc.Close()
			docXML = b.String()
		}
	}
	for name, found := range want {
		if !found {
			t.Errorf("missing part %s", name)
		}
	}
	if !strings.Contains(docXML, "&lt; &gt; &amp;") {
		t.Errorf("xml not escaped properly: %s", docXML)
	}
	if !strings.Contains(docXML, "第一章 背景") {
		t.Errorf("heading missing")
	}
	t.Logf("docx ok: %d bytes, %d parts", len(data), len(zr.File))
}
