package config

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

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

func TestLoadFromDirDefaultsToDevYAML(t *testing.T) {
	configDir := t.TempDir()
	writeConfig(t, configDir, "agent.dev.yaml", "development", "18080", "postgres://dev", "./dev-files", "dev-auth", "dev-system", "dev-ai")
	t.Setenv("SENLIN_APP_MODE", "")
	t.Setenv("PORT", "9999")

	cfg, err := LoadFromDir(configDir)

	require.NoError(t, err)
	require.Equal(t, "development", cfg.Env)
	require.Equal(t, "18080", cfg.Port)
	require.Equal(t, "postgres://dev", cfg.DSN)
	require.Equal(t, "./dev-files", cfg.StorageDir)
	require.Equal(t, "dev-auth", cfg.AuthSecret)
	require.Equal(t, "dev-system", cfg.SystemAIKey)
	require.Equal(t, "dev-ai", cfg.AIKeyEncryptionSecret)
}

func TestLoadFromDirUsesSENLINAppMode(t *testing.T) {
	configDir := t.TempDir()
	writeConfig(t, configDir, "agent.dev.yaml", "development", "18080", "postgres://dev", "./dev-files", "dev-auth", "", "dev-ai")
	writeConfig(t, configDir, "agent.prod.yaml", "production", "80", "postgres://prod", "/data/files", "prod-auth", "prod-system", "prod-ai")
	t.Setenv("SENLIN_APP_MODE", "prod")

	cfg, err := LoadFromDir(configDir)

	require.NoError(t, err)
	require.Equal(t, "production", cfg.Env)
	require.Equal(t, "80", cfg.Port)
	require.Equal(t, "postgres://prod", cfg.DSN)
	require.Equal(t, "/data/files", cfg.StorageDir)
	require.Equal(t, "prod-auth", cfg.AuthSecret)
	require.Equal(t, "prod-system", cfg.SystemAIKey)
	require.Equal(t, "prod-ai", cfg.AIKeyEncryptionSecret)
}

func writeConfig(t *testing.T, dir string, name string, env string, port string, databaseURL string, storageDir string, authSecret string, systemAIKey string, aiKeySecret string) {
	t.Helper()
	content := []byte("env: " + env + "\n" +
		"port: \"" + port + "\"\n" +
		"dsn: \"" + databaseURL + "\"\n" +
		"storage_dir: \"" + storageDir + "\"\n" +
		"auth_secret: \"" + authSecret + "\"\n" +
		"system_ai_key: \"" + systemAIKey + "\"\n" +
		"ai_key_encryption_secret: \"" + aiKeySecret + "\"\n")
	require.NoError(t, os.WriteFile(filepath.Join(dir, name), content, 0o600))
}
