package logger

import (
	"bytes"
	"log/slog"
	"strings"
	"testing"
)

func TestResolveBackendLogLevel_DefaultsByAppEnv(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		name      string
		appEnv    string
		wantLevel slog.Level
	}{
		{name: "dev uses debug", appEnv: "dev", wantLevel: slog.LevelDebug},
		{name: "local uses debug", appEnv: "local", wantLevel: slog.LevelDebug},
		{name: "development uses debug", appEnv: "development", wantLevel: slog.LevelDebug},
		{name: "stage uses info", appEnv: "stage", wantLevel: slog.LevelInfo},
		{name: "production uses info", appEnv: "production", wantLevel: slog.LevelInfo},
	}

	for _, tc := range testCases {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()

			got := ResolveBackendLogLevel(tc.appEnv, "")
			if got != tc.wantLevel {
				t.Fatalf("expected level %v, got %v", tc.wantLevel, got)
			}
		})
	}
}

func TestResolveBackendLogLevel_OverrideWins(t *testing.T) {
	t.Parallel()

	got := ResolveBackendLogLevel("production", "debug")
	if got != slog.LevelDebug {
		t.Fatalf("expected debug override, got %v", got)
	}

	got = ResolveBackendLogLevel("dev", "warn")
	if got != slog.LevelWarn {
		t.Fatalf("expected warn override, got %v", got)
	}
}

func TestInit_UsesResolvedBackendLogLevel(t *testing.T) {
	var buf bytes.Buffer
	previous := slog.Default()
	defer slog.SetDefault(previous)

	Init(Config{
		ServiceName:   "baron-sso",
		Environment:   "stage",
		LevelOverride: "debug",
		Output:        &buf,
	})

	slog.Debug("debug message should be visible")

	if !strings.Contains(buf.String(), "debug message should be visible") {
		t.Fatalf("expected debug log to be written, got=%s", buf.String())
	}
}
