package config_test

import (
	"os"
	"path/filepath"
	"testing"

	"git.godopu.com/lab/landing_page/backend/internal/config"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestConfigDefaults(t *testing.T) {
	// Clear env
	_ = os.Unsetenv("PORT")
	_ = os.Unsetenv("HOST")
	_ = os.Unsetenv("DB_PATH")
	_ = os.Unsetenv("GIN_MODE")
	_ = os.Unsetenv("CORS_ALLOW_ORIGINS")
	_ = os.Unsetenv("AUTO_MIGRATE")
	_ = os.Unsetenv("ADMIN_TOKEN")

	cfg := config.Load()
	assert.Equal(t, 8080, cfg.Port)
	assert.Equal(t, "0.0.0.0", cfg.Host)
	assert.Equal(t, "anl.db", cfg.DBPath)
	assert.Equal(t, "release", cfg.GinMode)
	assert.Equal(t, "*", cfg.CORSAllowOrigins)
	assert.True(t, cfg.AutoMigrate)
	assert.Equal(t, "", cfg.AdminToken)
	assert.Equal(t, "0.0.0.0:8080", cfg.Address())
}

func TestConfigEnvOverrides(t *testing.T) {
	_ = os.Setenv("PORT", "9090")
	_ = os.Setenv("HOST", "127.0.0.1")
	_ = os.Setenv("DB_PATH", "/tmp/custom.db")
	_ = os.Setenv("GIN_MODE", "debug")
	_ = os.Setenv("CORS_ALLOW_ORIGINS", "https://anl.knu.ac.kr")
	_ = os.Setenv("AUTO_MIGRATE", "false")
	_ = os.Setenv("ADMIN_TOKEN", "super-secret-token")
	defer func() {
		_ = os.Unsetenv("PORT")
		_ = os.Unsetenv("HOST")
		_ = os.Unsetenv("DB_PATH")
		_ = os.Unsetenv("GIN_MODE")
		_ = os.Unsetenv("CORS_ALLOW_ORIGINS")
		_ = os.Unsetenv("AUTO_MIGRATE")
		_ = os.Unsetenv("ADMIN_TOKEN")
	}()

	cfg := config.Load()
	assert.Equal(t, 9090, cfg.Port)
	assert.Equal(t, "127.0.0.1", cfg.Host)
	assert.Equal(t, "/tmp/custom.db", cfg.DBPath)
	assert.Equal(t, "debug", cfg.GinMode)
	assert.Equal(t, "https://anl.knu.ac.kr", cfg.CORSAllowOrigins)
	assert.False(t, cfg.AutoMigrate)
	assert.Equal(t, "super-secret-token", cfg.AdminToken)
	assert.Equal(t, "127.0.0.1:9090", cfg.Address())
}

func TestLoadEnvFile(t *testing.T) {
	tmpDir := t.TempDir()
	envPath := filepath.Join(tmpDir, ".env")
	envContent := `
# Sample comment
TEST_CUSTOM_KEY="hello_world"
TEST_PORT_KEY=8888
INVALID_LINE_WITHOUT_EQUALS
`
	err := os.WriteFile(envPath, []byte(envContent), 0644)
	require.NoError(t, err)

	_ = os.Unsetenv("TEST_CUSTOM_KEY")
	_ = os.Unsetenv("TEST_PORT_KEY")
	defer func() {
		_ = os.Unsetenv("TEST_CUSTOM_KEY")
		_ = os.Unsetenv("TEST_PORT_KEY")
	}()

	config.LoadEnvFile(envPath)
	assert.Equal(t, "hello_world", os.Getenv("TEST_CUSTOM_KEY"))
	assert.Equal(t, "8888", os.Getenv("TEST_PORT_KEY"))
}
