package config_test

import (
	"os"
	"testing"

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

	"github.com/veylant/ia-gateway/internal/config"
)

func TestLoad_Defaults(t *testing.T) {
	// No config.yaml in the test working directory — relies on defaults.
	cfg, err := config.Load()
	require.NoError(t, err)

	assert.Equal(t, 8090, cfg.Server.Port)
	assert.Equal(t, 30, cfg.Server.ShutdownTimeout)
	assert.Equal(t, "development", cfg.Server.Env)
	assert.Equal(t, "info", cfg.Log.Level)
	assert.Equal(t, "json", cfg.Log.Format)
	assert.Equal(t, "https://api.openai.com/v1", cfg.Providers.OpenAI.BaseURL)
	assert.Equal(t, 30, cfg.Providers.OpenAI.TimeoutSeconds)
	assert.Equal(t, 100, cfg.Providers.OpenAI.MaxConns)
	assert.True(t, cfg.Metrics.Enabled)
	assert.Equal(t, "/metrics", cfg.Metrics.Path)
}

func TestLoad_EnvVarOverride(t *testing.T) {
	t.Setenv("VEYLANT_SERVER_PORT", "9999")
	t.Setenv("VEYLANT_LOG_LEVEL", "debug")
	t.Setenv("VEYLANT_SERVER_ENV", "production")

	cfg, err := config.Load()
	require.NoError(t, err)

	assert.Equal(t, 9999, cfg.Server.Port)
	assert.Equal(t, "debug", cfg.Log.Level)
	assert.Equal(t, "production", cfg.Server.Env)
}

func TestLoad_NoConfigFileIsNotAnError(t *testing.T) {
	// Change to a temp directory with no config.yaml to confirm graceful fallback.
	dir := t.TempDir()
	origDir, _ := os.Getwd()
	require.NoError(t, os.Chdir(dir))
	t.Cleanup(func() { _ = os.Chdir(origDir) })

	cfg, err := config.Load()
	require.NoError(t, err)
	assert.NotNil(t, cfg)
}
