package realname

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCloudMarketProviderStartVerified(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			t.Fatalf("请求方法不正确：%s", r.Method)
		}
		if r.Header.Get("Authorization") != "APPCODE test-code" {
			t.Fatalf("APPCODE 请求头不正确：%s", r.Header.Get("Authorization"))
		}
		if r.URL.Query().Get("name") != "张三" {
			t.Fatalf("姓名参数不正确：%s", r.URL.Query().Get("name"))
		}
		if r.URL.Query().Get("id_number") != "110101199001011234" {
			t.Fatalf("身份证参数不正确：%s", r.URL.Query().Get("id_number"))
		}
		_, _ = w.Write([]byte(`{"request_id":"TID123","status":"OK","result":1}`))
	}))
	defer server.Close()

	provider, err := NewCloudMarketProvider(CloudMarketConfig{
		URL:     server.URL,
		AppCode: "test-code",
	})
	if err != nil {
		t.Fatalf("创建 Provider 失败：%v", err)
	}

	result, err := provider.Start(t.Context(), StartRequest{
		UserID: 1,
		Name:   "张三",
		IDNo:   "110101199001011234",
	})
	if err != nil {
		t.Fatalf("实名认证请求失败：%v", err)
	}
	if result.Status != StatusVerified {
		t.Fatalf("状态不正确：%s", result.Status)
	}
	if result.ProviderOrderNo != "TID123" {
		t.Fatalf("请求流水不正确：%s", result.ProviderOrderNo)
	}
	if result.VerifiedAt == nil {
		t.Fatal("通过时间不能为空")
	}
}

func TestCloudMarketProviderStartRejected(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(`{"request_id":"TID456","status":"OK","result":"2"}`))
	}))
	defer server.Close()

	provider, err := NewCloudMarketProvider(CloudMarketConfig{
		URL:     server.URL,
		AppCode: "test-code",
	})
	if err != nil {
		t.Fatalf("创建 Provider 失败：%v", err)
	}

	result, err := provider.Start(t.Context(), StartRequest{
		UserID: 1,
		Name:   "李四",
		IDNo:   "110101199001011234",
	})
	if err != nil {
		t.Fatalf("实名认证请求失败：%v", err)
	}
	if result.Status != StatusRejected {
		t.Fatalf("状态不正确：%s", result.Status)
	}
	if result.FailReason == "" {
		t.Fatal("拒绝原因不能为空")
	}
}

func TestCloudMarketProviderStartRateLimited(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(`{"request_id":"TID789","status":"OK","result":110}`))
	}))
	defer server.Close()

	provider, err := NewCloudMarketProvider(CloudMarketConfig{
		URL:     server.URL,
		AppCode: "test-code",
	})
	if err != nil {
		t.Fatalf("创建 Provider 失败：%v", err)
	}

	_, err = provider.Start(t.Context(), StartRequest{
		UserID: 1,
		Name:   "王五",
		IDNo:   "110101199001011234",
	})
	if !errors.Is(err, ErrProviderRateLimited) {
		t.Fatalf("期望限流错误，实际：%v", err)
	}
}
