package streaming_api_test

import (
	"encoding/json"
	"net/http"
	"strings"
	"testing"

	"github.com/nexuscrm/tests/contract/internal/liveapi"
	"github.com/stretchr/testify/require"
)

func cometDVersion(t *testing.T) string {
	t.Helper()

	cfg := liveapi.LoadConfig(t)
	return strings.TrimPrefix(cfg.APIVersion, "v")
}

func handshakeClientID(t *testing.T, client *liveapi.Client, baseURL, version string, sandboxSkipMsg string) string {
	t.Helper()

	resp, err := client.DoJSON(http.MethodPost, baseURL+"/cometd/"+version+"/handshake", []map[string]any{
		{
			"channel":                  "/meta/handshake",
			"version":                  "1.0",
			"minimumVersion":           "1.0",
			"supportedConnectionTypes": []string{"long-polling"},
		},
	})
	require.NoError(t, err)
	if sandboxSkipMsg != "" && resp.StatusCode == http.StatusNotFound {
		t.Skip(sandboxSkipMsg)
	}
	require.Equal(t, http.StatusOK, resp.StatusCode)

	raw := liveapi.ReadBody(t, resp)
	var body []struct {
		Channel                  string   `json:"channel"`
		Version                  string   `json:"version"`
		SupportedConnectionTypes []string `json:"supportedConnectionTypes"`
		ClientID                 string   `json:"clientId"`
		Successful               bool     `json:"successful"`
	}
	require.NoError(t, json.Unmarshal(raw, &body))
	require.Len(t, body, 1)
	require.Equal(t, "/meta/handshake", body[0].Channel)
	require.True(t, body[0].Successful)
	require.NotEmpty(t, body[0].ClientID)
	require.Contains(t, body[0].SupportedConnectionTypes, "long-polling")
	return body[0].ClientID
}
