package middleware

import (
	"encoding/json"
	"strings"
	"testing"
)

func TestPaymentIntegrationSecretsAreRedacted(t *testing.T) {
	raw := []byte(`{"enabled":true,"config":{"app_id":"app","mch_key":"merchant-secret","api_v3_key":"v3-secret","client_cert":"certificate","client_key":"private-key","platform_cert":"platform-certificate","credential_code":"credential","webhook_id":"webhook"}}`)
	redacted := redactJSON(raw, "application/json", 4096)
	var payload struct {
		Config map[string]string `json:"config"`
	}
	if err := json.Unmarshal([]byte(redacted), &payload); err != nil {
		t.Fatalf("decode redacted payload: %v", err)
	}
	for _, key := range []string{"mch_key", "api_v3_key", "client_cert", "client_key", "platform_cert", "credential_code", "webhook_id"} {
		if payload.Config[key] != "***" {
			t.Fatalf("payment secret %q was not redacted: %s", key, redacted)
		}
	}
	if !strings.Contains(redacted, `"app_id":"app"`) {
		t.Fatalf("non-secret integration field was removed: %s", redacted)
	}
}

func TestPaymentOperationsAreAuditedWithRouterPrefix(t *testing.T) {
	for _, route := range []struct {
		method string
		path   string
	}{
		{method: "PUT", path: "/api/integration/configs/payment/alipay"},
		{method: "POST", path: "/api/payment/refund"},
		{method: "POST", path: "/api/payment/fulfill"},
		{method: "POST", path: "/api/payment/providers/alipay/test"},
	} {
		if !recordsOperation(route.method, route.path) {
			t.Fatalf("payment operation was not audited: %s %s", route.method, route.path)
		}
	}
}

func TestPaymentIntegrationConfigUsesRouteLevelSummary(t *testing.T) {
	raw := []byte(`{"enabled":true,"config":{"key":"secret","custom_certificate":"certificate"}}`)
	summary := paymentConfigSummary(raw)
	if strings.Contains(summary, "secret") || strings.Contains(summary, "certificate") {
		t.Fatalf("payment configuration summary leaked payload: %s", summary)
	}
	if !isPaymentIntegrationConfigWrite("PUT", "/api/integration/configs/payment/saobei") {
		t.Fatal("payment configuration write route was not recognized")
	}
	if isPaymentIntegrationConfigWrite("PUT", "/api/integration/configs/mq/emqx") {
		t.Fatal("non-payment integration was treated as payment configuration")
	}
}
