package debug

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"testing"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
)

func TestFilesystemRecorderWritesWithinTraceRoot(t *testing.T) {
	root := t.TempDir()
	recorder, err := NewFilesystemRecorder(root)
	if err != nil {
		t.Fatal(err)
	}
	if err := recorder.WriteBytes("attempt/data", []byte("payload")); err != nil {
		t.Fatal(err)
	}
	info, err := os.Stat(filepath.Join(root, "attempt", "data"))
	if err != nil {
		t.Fatal(err)
	}
	if info.Mode().Perm() != 0o600 {
		t.Fatalf("mode=%#o", info.Mode().Perm())
	}
	if err := recorder.WriteBytes("../outside", nil); err == nil {
		t.Fatal("accepted traversal")
	}
}

func TestFilesystemRecorderPropagatesWriteFailures(t *testing.T) {
	root := filepath.Join(t.TempDir(), "trace")
	if err := os.WriteFile(root, []byte("not a directory"), 0o600); err != nil {
		t.Fatal(err)
	}
	recorder, err := NewFilesystemRecorder(root)
	if err != nil {
		t.Fatal(err)
	}
	if err := recorder.WriteBytes("attempt/data", []byte("payload")); err == nil {
		t.Fatal("WriteBytes concealed a trace-root write failure")
	}
}

func TestSynchronizedFilesystemRecorderSupportsConcurrentWrites(t *testing.T) {
	root := t.TempDir()
	recorder, err := NewFilesystemRecorder(root)
	if err != nil {
		t.Fatal(err)
	}
	recorder = pipeline.SynchronizedDebugRecorder(recorder)

	const writes = 16
	var wg sync.WaitGroup
	errs := make(chan error, writes)
	for i := 0; i < writes; i++ {
		i := i
		wg.Add(1)
		go func() {
			defer wg.Done()
			errs <- recorder.WriteBytes(fmt.Sprintf("attempt/%02d/data", i), []byte("payload"))
		}()
	}
	wg.Wait()
	close(errs)
	for err := range errs {
		if err != nil {
			t.Fatal(err)
		}
	}
	for i := 0; i < writes; i++ {
		if _, err := os.Stat(filepath.Join(root, "attempt", fmt.Sprintf("%02d", i), "data")); err != nil {
			t.Fatalf("trace artifact %d: %v", i, err)
		}
	}
}
