package applog

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

// The log has to be bounded WHILE RUNNING, not only at startup. The CI-V wire
// trace left on for a day wrote 416 MB, and nothing would have stopped it
// before the disk did.
func TestRotatesMidSession(t *testing.T) {
	orig := maxLogBytes
	maxLogBytes = 8 * 1024 // small, so the test costs milliseconds
	defer func() { maxLogBytes = orig }()

	dir := t.TempDir()
	p, err := Init(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer Close()

	line := strings.Repeat("x", 256)
	for i := 0; i < 100; i++ { // ~25 KB: several times the limit
		Printf("%s", line)
	}

	if _, err := os.Stat(p + ".1"); err != nil {
		t.Fatalf("no previous generation kept: %v", err)
	}
	fi, err := os.Stat(p)
	if err != nil {
		t.Fatal(err)
	}
	if fi.Size() > maxLogBytes {
		t.Fatalf("current log is %d bytes, over the %d limit — it did not roll over", fi.Size(), maxLogBytes)
	}
	// The new file says where the rest went: a log that starts mid-sentence with
	// no explanation is how an operator concludes the app lost its history.
	b, err := os.ReadFile(p)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(b), "continued from "+filepath.Base(p)+".1") {
		t.Error("the new file does not point at the one it continues")
	}
}
