// Copyright 2025, IPng Networks GmbH, Pim van Pelt <pim@ipng.ch>

package logger

import (
	"bytes"
	"io"
	"os"
	"strings"
	"testing"

	"govpp-snmp-agentx/config"
)

func TestPrintf(t *testing.T) {
	// Capture stdout
	oldStdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w

	Printf("test message: %s", "hello")

	// Close writer and restore stdout
	w.Close()
	os.Stdout = oldStdout

	// Read captured output
	var buf bytes.Buffer
	_, _ = io.Copy(&buf, r)
	output := buf.String()

	// Check output format: "INFO file.go:function message"
	if !strings.HasPrefix(output, "INFO ") {
		t.Errorf("Expected output to start with 'INFO ', got: %s", output)
	}
	
	if !strings.Contains(output, "logger_test.go:logger.TestPrintf") {
		t.Errorf("Expected output to contain caller info, got: %s", output)
	}
	
	if !strings.Contains(output, "test message: hello") {
		t.Errorf("Expected output to contain message, got: %s", output)
	}
}

func TestDebugfWithDebugEnabled(t *testing.T) {
	// Save original debug state
	originalDebug := config.Debug
	defer func() { config.Debug = originalDebug }()

	// Enable debug
	config.Debug = true

	// Capture stdout
	oldStdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w

	Debugf("debug message: %s", "test")

	// Close writer and restore stdout
	w.Close()
	os.Stdout = oldStdout

	// Read captured output
	var buf bytes.Buffer
	_, _ = io.Copy(&buf, r)
	output := buf.String()

	// Check output format: "DEBUG file.go:function message"
	if !strings.HasPrefix(output, "DEBUG ") {
		t.Errorf("Expected output to start with 'DEBUG ', got: %s", output)
	}
	
	if !strings.Contains(output, "debug message: test") {
		t.Errorf("Expected output to contain message, got: %s", output)
	}
}

func TestDebugfWithDebugDisabled(t *testing.T) {
	// Save original debug state
	originalDebug := config.Debug
	defer func() { config.Debug = originalDebug }()

	// Disable debug
	config.Debug = false

	// Capture stdout
	oldStdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w

	Debugf("debug message: %s", "test")

	// Close writer and restore stdout
	w.Close()
	os.Stdout = oldStdout

	// Read captured output
	var buf bytes.Buffer
	_, _ = io.Copy(&buf, r)
	output := buf.String()

	// Should be empty when debug is disabled
	if output != "" {
		t.Errorf("Expected no output when debug is disabled, got: %s", output)
	}
}

func TestSync(t *testing.T) {
	// Test that Sync doesn't panic (it's a no-op now)
	Sync()
}