package main

import (
	"baron-sso-backend/internal/service"
	"os"
	"path/filepath"
	"testing"
)

func TestGetEnvFileOrValueReadsSecretFile(t *testing.T) {
	t.Setenv("WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY", "inline-value")

	secretPath := filepath.Join(t.TempDir(), "worksmobile-private-key.pem")
	want := "-----BEGIN PRIVATE KEY-----\nsecret\n-----END PRIVATE KEY-----\n"
	if err := os.WriteFile(secretPath, []byte(want), 0o600); err != nil {
		t.Fatalf("failed to write secret file: %v", err)
	}
	t.Setenv("WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE", secretPath)

	got, err := getEnvFileOrValue("WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE", "WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY", "")
	if err != nil {
		t.Fatalf("getEnvFileOrValue returned error: %v", err)
	}
	if got != want {
		t.Fatalf("secret value = %q, want file content", got)
	}
}

func TestGetEnvFileOrValueFallsBackToRawEnv(t *testing.T) {
	t.Setenv("WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY", "inline-value")
	t.Setenv("WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE", "")

	got, err := getEnvFileOrValue("WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE", "WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY", "")
	if err != nil {
		t.Fatalf("getEnvFileOrValue returned error: %v", err)
	}
	if got != "inline-value" {
		t.Fatalf("secret value = %q, want raw env value", got)
	}
}

func TestConfigureWorksmobileClientFromEnvOverridesAPIBaseURL(t *testing.T) {
	t.Setenv("WORKS_ADMIN_API_BASE_URL", "https://proxy.example.com/works")
	client := service.NewWorksmobileHTTPClientWithTokens("", "")

	configureWorksmobileClientFromEnv(client)

	if client.BaseURL != "https://proxy.example.com/works" {
		t.Fatalf("BaseURL = %q, want env override", client.BaseURL)
	}
}
