package logging

import (
	"encoding/json"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap"
)

func TestAggregationConfig_Default(t *testing.T) {
	config := DefaultAggregationConfig()
	assert.NotNil(t, config)
	assert.False(t, config.Enabled)
	assert.Equal(t, 100, config.BatchSize)
	assert.Equal(t, 5*time.Second, config.FlushInterval)
	assert.Equal(t, 10*time.Second, config.Timeout)
	assert.NotNil(t, config.Labels)
}

func TestNewLoggerWithAggregation_Disabled(t *testing.T) {
	config := DefaultAggregationConfig()
	config.Enabled = false

	logger, err := NewLoggerWithAggregation("development", "INFO", config)
	require.NoError(t, err)
	assert.NotNil(t, logger)

	// Le logger devrait fonctionner normalement même si l'agrégation est désactivée
	logger.Info("Test log message", zap.String("test", "value"))
}

func TestNewLoggerWithAggregation_InvalidEndpoint(t *testing.T) {
	config := DefaultAggregationConfig()
	config.Enabled = true
	config.EndpointURL = "" // URL vide

	// Devrait créer un logger sans agrégation si l'endpoint est vide
	logger, err := NewLoggerWithAggregation("development", "INFO", config)
	require.NoError(t, err)
	assert.NotNil(t, logger)
}

func TestLogEntry_MarshalJSON(t *testing.T) {
	entry := logEntry{
		Timestamp: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC),
		Level:     "INFO",
		Message:   "Test message",
		Fields: map[string]interface{}{
			"key1": "value1",
			"key2": 42,
		},
		Labels: map[string]string{
			"service": "test",
			"env":     "development",
		},
	}

	data, err := json.Marshal(entry)
	require.NoError(t, err)
	assert.Contains(t, string(data), "Test message")
	assert.Contains(t, string(data), "INFO")
}

func TestNewLoggerWithAggregation_Production(t *testing.T) {
	config := DefaultAggregationConfig()
	config.Enabled = false // Désactiver pour le test (pas de serveur réel)

	logger, err := NewLoggerWithAggregation("production", "INFO", config)
	require.NoError(t, err)
	assert.NotNil(t, logger)

	// Vérifier que le logger fonctionne
	logger.Info("Production log test",
		zap.String("component", "test"),
		zap.Int("value", 42),
	)
}

func TestNewLoggerWithAggregation_Development(t *testing.T) {
	config := DefaultAggregationConfig()
	config.Enabled = false // Désactiver pour le test

	logger, err := NewLoggerWithAggregation("development", "DEBUG", config)
	require.NoError(t, err)
	assert.NotNil(t, logger)

	// Vérifier que le logger fonctionne en mode développement
	logger.Debug("Debug log test",
		zap.String("component", "test"),
	)
}
