package service

import (
	"context"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
	"time"

	"github.com/spf13/viper"
)

func TestBuildSalesforceTokenBodyEncodesSpecialCharacters(t *testing.T) {
	body := buildSalesforceTokenBody("client", "secret", "user@example.com", "Zxp19961216&")

	values, err := url.ParseQuery(body)
	if err != nil {
		t.Fatalf("token body should be valid form encoding: %v", err)
	}

	if got := values.Get("password"); got != "Zxp19961216&" {
		t.Fatalf("password should round-trip through form encoding, got %q", got)
	}
}

func TestBuildNexusCRMTokenBodyUsesClientCredentials(t *testing.T) {
	body := buildNexusCRMTokenBody("client", "secret&value", "api")

	values, err := url.ParseQuery(body)
	if err != nil {
		t.Fatalf("token body should be valid form encoding: %v", err)
	}

	if got := values.Get("grant_type"); got != "client_credentials" {
		t.Fatalf("grant_type = %q, want client_credentials", got)
	}
	if got := values.Get("client_secret"); got != "secret&value" {
		t.Fatalf("client_secret should round-trip through form encoding, got %q", got)
	}
	if got := values.Get("scope"); got != "api" {
		t.Fatalf("scope = %q, want api", got)
	}
}

func TestFetchNexusCRMTokenUsesEnvSecret(t *testing.T) {
	viper.Reset()
	t.Cleanup(viper.Reset)
	t.Setenv("NEXUSCRM_TEST_SECRET", "secret-from-env")

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/services/oauth2/token" {
			t.Fatalf("path = %q, want /services/oauth2/token", r.URL.Path)
		}
		if r.Method != http.MethodPost {
			t.Fatalf("method = %q, want POST", r.Method)
		}
		if got := r.Header.Get("Content-Type"); got != "application/x-www-form-urlencoded" {
			t.Fatalf("content-type = %q, want application/x-www-form-urlencoded", got)
		}
		if err := r.ParseForm(); err != nil {
			t.Fatalf("ParseForm failed: %v", err)
		}
		assertFormValue(t, r.Form, "grant_type", "client_credentials")
		assertFormValue(t, r.Form, "client_id", "test-client")
		assertFormValue(t, r.Form, "client_secret", "secret-from-env")
		assertFormValue(t, r.Form, "scope", "api")

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"access_token":"nexus-token"}`))
	}))
	defer server.Close()

	viper.Set("nexuscrm.base_url", server.URL+"/")
	viper.Set("nexuscrm.client_id", "test-client")
	viper.Set("nexuscrm.client_secret_env", "NEXUSCRM_TEST_SECRET")
	viper.Set("nexuscrm.scope", "api")

	token, expiry, err := fetchNexusCRMToken(context.Background())
	if err != nil {
		t.Fatalf("fetchNexusCRMToken returned error: %v", err)
	}
	if token != "nexus-token" {
		t.Fatalf("token = %q, want nexus-token", token)
	}
	if !expiry.After(time.Now()) {
		t.Fatalf("expiry should be in the future, got %s", expiry)
	}
}

func TestFetchNexusCRMTokenRequiresEnvSecret(t *testing.T) {
	viper.Reset()
	t.Cleanup(viper.Reset)

	viper.Set("nexuscrm.base_url", "https://nexuscrm-new-prod.pingcap.com")
	viper.Set("nexuscrm.client_id", "test-client")
	viper.Set("nexuscrm.client_secret_env", "NEXUSCRM_TEST_SECRET")

	_, _, err := fetchNexusCRMToken(context.Background())
	if err == nil {
		t.Fatal("expected error when NexusCRM client secret env var is missing")
	}
}

func assertFormValue(t *testing.T, values url.Values, key, want string) {
	t.Helper()

	if got := values.Get(key); got != want {
		t.Fatalf("%s = %q, want %q", key, got, want)
	}
}
