package observability_test

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

	"iop/packages/go/observability"
)

func TestNewLoggerWithFile_EmptyPathFallsBackToStderr(t *testing.T) {
	logger, err := observability.NewLoggerWithFile("info", false, "")
	if err != nil {
		t.Fatalf("NewLoggerWithFile: %v", err)
	}
	if logger == nil {
		t.Fatal("logger is nil")
	}
	_ = logger.Sync()
}

func TestNewLoggerWithFile_CreatesParentDirAndFile(t *testing.T) {
	dir := t.TempDir()
	logPath := filepath.Join(dir, "logs", "edge.log")

	logger, err := observability.NewLoggerWithFile("info", false, logPath)
	if err != nil {
		t.Fatalf("NewLoggerWithFile: %v", err)
	}
	logger.Info("hello-from-test")
	_ = logger.Sync()

	info, err := os.Stat(logPath)
	if err != nil {
		t.Fatalf("stat log file: %v", err)
	}
	if info.IsDir() {
		t.Fatalf("log path is a directory: %s", logPath)
	}
	if info.Size() == 0 {
		t.Fatalf("log file is empty: %s", logPath)
	}
	contents, err := os.ReadFile(logPath)
	if err != nil {
		t.Fatalf("read log file: %v", err)
	}
	if !strings.Contains(string(contents), "hello-from-test") {
		t.Fatalf("log file missing entry; contents=%q", string(contents))
	}
}

func TestNewLoggerWithFile_AppendsToExistingFile(t *testing.T) {
	dir := t.TempDir()
	logPath := filepath.Join(dir, "edge.log")

	first, err := observability.NewLoggerWithFile("info", false, logPath)
	if err != nil {
		t.Fatalf("first NewLoggerWithFile: %v", err)
	}
	first.Info("entry-one")
	_ = first.Sync()

	second, err := observability.NewLoggerWithFile("info", false, logPath)
	if err != nil {
		t.Fatalf("second NewLoggerWithFile: %v", err)
	}
	second.Info("entry-two")
	_ = second.Sync()

	contents, err := os.ReadFile(logPath)
	if err != nil {
		t.Fatalf("read log file: %v", err)
	}
	if !strings.Contains(string(contents), "entry-one") || !strings.Contains(string(contents), "entry-two") {
		t.Fatalf("expected both entries in log file; contents=%q", string(contents))
	}
}
