package gateway

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestQueryCardStatus_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
			Data: json.RawMessage(`{"iccid":"898608070422D0010269","cardStatus":"正常"}`),
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	result, err := client.QueryCardStatus(ctx, &CardStatusReq{
		CardNo: "898608070422D0010269",
	})

	if err != nil {
		t.Fatalf("QueryCardStatus() error = %v", err)
	}

	if result.ICCID != "898608070422D0010269" {
		t.Errorf("ICCID = %s, want 898608070422D0010269", result.ICCID)
	}
	if result.CardStatus != "正常" {
		t.Errorf("CardStatus = %s, want 正常", result.CardStatus)
	}
}

func TestQueryCardStatus_InvalidResponse(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
			Data: json.RawMessage(`invalid json`),
		}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	_, err := client.QueryCardStatus(ctx, &CardStatusReq{CardNo: "test"})
	if err == nil {
		t.Fatal("QueryCardStatus() expected JSON parse error")
	}

	if !strings.Contains(err.Error(), "解析") {
		t.Errorf("error should contain '解析', got: %v", err)
	}
}

func TestQueryFlow_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
			Data: json.RawMessage(`{"usedFlow":1024,"unit":"MB"}`),
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	result, err := client.QueryFlow(ctx, &FlowQueryReq{
		CardNo: "898608070422D0010269",
	})

	if err != nil {
		t.Fatalf("QueryFlow() error = %v", err)
	}

	if result.UsedFlow != 1024 {
		t.Errorf("UsedFlow = %d, want 1024", result.UsedFlow)
	}
	if result.Unit != "MB" {
		t.Errorf("Unit = %s, want MB", result.Unit)
	}
}

func TestQueryFlow_BusinessError(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 404,
			Msg:  "卡号不存在",
		}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	_, err := client.QueryFlow(ctx, &FlowQueryReq{CardNo: "invalid"})
	if err == nil {
		t.Fatal("QueryFlow() expected business error")
	}

	if !strings.Contains(err.Error(), "业务错误") {
		t.Errorf("error should contain '业务错误', got: %v", err)
	}
}

func TestQueryRealnameStatus_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
			Data: json.RawMessage(`{"status":"已实名"}`),
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	result, err := client.QueryRealnameStatus(ctx, &CardStatusReq{
		CardNo: "898608070422D0010269",
	})

	if err != nil {
		t.Fatalf("QueryRealnameStatus() error = %v", err)
	}

	if result.Status != "已实名" {
		t.Errorf("Status = %s, want 已实名", result.Status)
	}
}

func TestStopCard_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
		}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	err := client.StopCard(ctx, &CardOperationReq{
		CardNo: "898608070422D0010269",
	})

	if err != nil {
		t.Fatalf("StopCard() error = %v", err)
	}
}

func TestStopCard_WithExtend(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{Code: 200, Msg: "成功"}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	err := client.StopCard(ctx, &CardOperationReq{
		CardNo: "898608070422D0010269",
		Extend: "test-extend",
	})

	if err != nil {
		t.Fatalf("StopCard() error = %v", err)
	}
}

func TestStartCard_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{Code: 200, Msg: "成功"}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	err := client.StartCard(ctx, &CardOperationReq{
		CardNo: "898608070422D0010269",
	})

	if err != nil {
		t.Fatalf("StartCard() error = %v", err)
	}
}

func TestStartCard_BusinessError(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{Code: 500, Msg: "操作失败"}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	err := client.StartCard(ctx, &CardOperationReq{CardNo: "test"})
	if err == nil {
		t.Fatal("StartCard() expected business error")
	}
}

func TestGetRealnameLink_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
			Data: json.RawMessage(`{"link":"https://realname.example.com/verify?token=abc123"}`),
		}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	result, err := client.GetRealnameLink(ctx, &CardStatusReq{
		CardNo: "898608070422D0010269",
	})

	if err != nil {
		t.Fatalf("GetRealnameLink() error = %v", err)
	}

	if result.Link != "https://realname.example.com/verify?token=abc123" {
		t.Errorf("Link = %s, want https://realname.example.com/verify?token=abc123", result.Link)
	}
}

func TestGetRealnameLink_InvalidResponse(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp := GatewayResponse{
			Code: 200,
			Msg:  "成功",
			Data: json.RawMessage(`{"invalid": "structure"}`),
		}
		json.NewEncoder(w).Encode(resp)
	}))
	defer server.Close()

	client := NewClient(server.URL, "testAppID", "testSecret")
	ctx := context.Background()

	result, err := client.GetRealnameLink(ctx, &CardStatusReq{CardNo: "test"})

	if err != nil {
		t.Fatalf("GetRealnameLink() unexpected error = %v", err)
	}
	if result.Link != "" {
		t.Errorf("Link = %s, want empty string", result.Link)
	}
}

func TestBatchQuery_NotImplemented(t *testing.T) {
	client := NewClient("https://test.example.com", "testAppID", "testSecret")
	ctx := context.Background()

	_, err := client.BatchQuery(ctx, &BatchQueryReq{
		CardNos: []string{"test1", "test2"},
	})

	if err == nil {
		t.Fatal("BatchQuery() expected not implemented error")
	}

	if !strings.Contains(err.Error(), "暂未实现") {
		t.Errorf("error should contain '暂未实现', got: %v", err)
	}
}
