package tencentrtc

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"strings"
	"testing"
	"time"
)

// TestRESTClientRemoveUserByStrRoomIDBuildsTencentCloudRequest 锁定 TRTC 字符串房间踢人的 API 3.0 请求形态。
func TestRESTClientRemoveUserByStrRoomIDBuildsTencentCloudRequest(t *testing.T) {
	var capturedBody map[string]any
	var capturedHeader http.Header
	client, err := NewRESTClient(RESTConfig{
		SDKAppID:  1400000001,
		SecretID:  "AKIDEXAMPLE",
		SecretKey: "secret",
		Region:    "ap-guangzhou",
		HTTPClient: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
			capturedHeader = request.Header.Clone()
			if err := json.NewDecoder(request.Body).Decode(&capturedBody); err != nil {
				t.Fatalf("decode request body failed: %v", err)
			}
			return &http.Response{
				StatusCode: http.StatusOK,
				Body:       io.NopCloser(bytes.NewReader([]byte(`{"Response":{"RequestId":"req-1"}}`))),
				Header:     make(http.Header),
			}, nil
		})},
		Now: func() time.Time { return time.Unix(1_700_000_000, 0).UTC() },
	})
	if err != nil {
		t.Fatalf("NewRESTClient failed: %v", err)
	}

	if err := client.RemoveUserByStrRoomID(context.Background(), "room_1001", 10002); err != nil {
		t.Fatalf("RemoveUserByStrRoomID failed: %v", err)
	}

	if capturedBody["SdkAppId"].(float64) != 1400000001 || capturedBody["RoomId"] != "room_1001" {
		t.Fatalf("unexpected remove user body: %+v", capturedBody)
	}
	users, ok := capturedBody["UserIds"].([]any)
	if !ok || len(users) != 1 || users[0] != "10002" {
		t.Fatalf("unexpected user ids: %+v", capturedBody)
	}
	if capturedHeader.Get("X-TC-Action") != removeUserByStrRoomAction || capturedHeader.Get("X-TC-Version") != trtcAPIVersion {
		t.Fatalf("unexpected tencent cloud headers: %+v", capturedHeader)
	}
	if !strings.HasPrefix(capturedHeader.Get("Authorization"), tencentCloudTC3Algorithm+" Credential=AKIDEXAMPLE/") {
		t.Fatalf("authorization header missing TC3 credential: %s", capturedHeader.Get("Authorization"))
	}
}

type roundTripFunc func(*http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
	return f(request)
}
