package payment

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	bizpayment "kra/internal/biz/payment"
)

func TestChinaumsCallbackAuthorizationVerification(t *testing.T) {
	profile := &vendorPaymentAdapter{profile: vendorChinaums}
	config := map[string]any{"app_id": "china-app", "app_key": "china-secret"}
	raw := []byte(`{"status":"SUCCESS","trade_no":"T-1"}`)
	timestamp, nonceValue := "1700000000", "nonce-1"
	digest := sha256.Sum256([]byte("china-app" + timestamp + nonceValue + string(raw) + "china-secret"))
	headers := map[string]string{
		"authorization": "OPEN-BODY-SIG AppId=china-app, Timestamp=" + timestamp + ", Nonce=" + nonceValue + ", Signature=" + hex.EncodeToString(digest[:]),
	}
	if err := profile.verify(nil, raw, headers, config); err != nil {
		t.Fatalf("valid Chinaums callback rejected: %v", err)
	}
	if err := profile.verify(nil, []byte(`{"status":"FAILED","trade_no":"T-1"}`), headers, config); err == nil {
		t.Fatal("tampered Chinaums callback accepted")
	}
	missingNonce := map[string]string{"Authorization": "OPEN-BODY-SIG AppId=china-app, Timestamp=" + timestamp + ", Signature=" + hex.EncodeToString(digest[:])}
	if err := profile.verify(nil, raw, missingNonce, config); err == nil || !strings.Contains(err.Error(), "信息不完整") {
		t.Fatalf("missing Chinaums signature component error = %v", err)
	}
	mismatchedApp := map[string]string{"Authorization": "OPEN-BODY-SIG AppId=other-app, Timestamp=" + timestamp + ", Nonce=" + nonceValue + ", Signature=" + hex.EncodeToString(digest[:])}
	if err := profile.verify(nil, raw, mismatchedApp, config); err == nil || !strings.Contains(err.Error(), "AppId") {
		t.Fatalf("mismatched Chinaums AppId error = %v", err)
	}
}

func TestVendorRefundMapsBusinessFailureStatus(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"status":"FAIL","message":"rejected"}`))
	}))
	defer server.Close()

	adapter := &vendorPaymentAdapter{provider: "vendor", profile: vendorSFT}
	result, err := adapter.Refund(context.Background(), &bizpayment.PaymentRefundRequest{TradeNo: "trade-1", RefundNo: "refund-1", Amount: 100, TotalAmount: 100, Currency: "CNY"}, map[string]any{
		"refund_url": server.URL,
		"app_key":    "secret",
	})
	if err != nil {
		t.Fatalf("Refund() error = %v", err)
	}
	if result == nil || result.Status != "failed" {
		t.Fatalf("Refund() result = %#v, want failed status", result)
	}
}

func TestVendorRefundRejectsUnknownBusinessStatus(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"status":"UNKNOWN"}`))
	}))
	defer server.Close()

	adapter := &vendorPaymentAdapter{provider: "vendor", profile: vendorSFT}
	result, err := adapter.Refund(context.Background(), &bizpayment.PaymentRefundRequest{TradeNo: "trade-1", RefundNo: "refund-1", Amount: 100, TotalAmount: 100, Currency: "CNY"}, map[string]any{
		"refund_url": server.URL,
		"app_key":    "secret",
	})
	if err == nil || !strings.Contains(err.Error(), "状态无法识别") {
		t.Fatalf("Refund() error = %v, want unknown-status error", err)
	}
	if result != nil {
		t.Fatalf("Refund() result = %#v, want nil", result)
	}
}
