package logger

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestNew_JSONHandler_WritesStructured(t *testing.T) {
	var buf bytes.Buffer
	log := New(Options{Format: FormatJSON, Level: LevelInfo, Writer: &buf})
	log.Info("hello", "key", "value")

	var got map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
	require.Equal(t, "hello", got["msg"])
	require.Equal(t, "value", got["key"])
	require.Equal(t, "INFO", got["level"])
}

func TestNew_TextHandler_HumanReadable(t *testing.T) {
	var buf bytes.Buffer
	log := New(Options{Format: FormatText, Level: LevelDebug, Writer: &buf})
	log.Debug("dev message", "x", 1)
	require.Contains(t, buf.String(), "dev message")
}

func TestNew_LevelFilter(t *testing.T) {
	var buf bytes.Buffer
	log := New(Options{Format: FormatJSON, Level: LevelWarn, Writer: &buf})
	log.Info("should be filtered")
	require.Empty(t, strings.TrimSpace(buf.String()))
}

func TestFromEnv_DevelopmentUsesText(t *testing.T) {
	var buf bytes.Buffer
	log := FromEnv("development", &buf)
	log.Debug("dev", "k", "v")
	out := buf.String()
	require.Contains(t, out, "dev")
	// text handler outputs key=value pairs (not JSON braces)
	require.NotContains(t, out, `"msg":`)
}

func TestFromEnv_NonDevelopmentUsesJSON(t *testing.T) {
	var buf bytes.Buffer
	log := FromEnv("production", &buf)
	// Debug should be filtered (JSON default level is Info)
	log.Debug("filtered")
	require.Empty(t, strings.TrimSpace(buf.String()))

	log.Info("prod")
	var got map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
	require.Equal(t, "prod", got["msg"])
}

func TestNew_AddSourceTrue_IncludesSourceField(t *testing.T) {
	var buf bytes.Buffer
	log := New(Options{Format: FormatJSON, Level: LevelInfo, Writer: &buf, AddSource: true})
	log.Info("with source")

	var got map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
	require.Contains(t, got, "source", "AddSource:true 时应有 source 字段")
}

func TestNew_AddSourceFalse_OmitsSourceField(t *testing.T) {
	var buf bytes.Buffer
	log := New(Options{Format: FormatJSON, Level: LevelInfo, Writer: &buf, AddSource: false})
	log.Info("without source")

	var got map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
	require.NotContains(t, got, "source")
}

func TestFromEnv_NonDevelopmentEnablesSource(t *testing.T) {
	var buf bytes.Buffer
	log := FromEnv("production", &buf)
	log.Info("prod log")

	var got map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
	require.Contains(t, got, "source", "production 应自动开 AddSource (spec §8.2)")
}
