package tooling_api_test

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

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

type toolingListResponse struct {
	Done      bool             `json:"done"`
	TotalSize int              `json:"totalSize"`
	Records   []map[string]any `json:"records"`
}

func fetchFirstToolingRecord(t testing.TB, path string) map[string]any {
	t.Helper()

	client := liveapi.NewAuthenticatedClient(t)
	resp, err := client.DoJSON(http.MethodGet, path, nil)
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	contracttest.AssertJSONContentType(t, resp)

	var body toolingListResponse
	liveapi.DecodeJSON(t, resp, &body)

	if len(body.Records) == 0 {
		t.Skipf("no Tooling API records available for %s", path)
	}

	return body.Records[0]
}

func requireStringFieldAny(t testing.TB, body map[string]any, fields ...string) string {
	t.Helper()

	for _, field := range fields {
		raw, ok := body[field]
		if !ok {
			continue
		}

		value, ok := raw.(string)
		require.True(t, ok, "field %s must be a string", field)
		value = strings.TrimSpace(value)
		require.NotEmpty(t, value, "field %s must not be empty", field)
		return value
	}

	require.FailNow(t, "missing string field", "expected one of %v", fields)
	return ""
}

func optionalStringField(body map[string]any, field string) (string, bool) {
	raw, ok := body[field]
	if !ok || raw == nil {
		return "", false
	}

	value, ok := raw.(string)
	if !ok {
		return "", false
	}

	value = strings.TrimSpace(value)
	if value == "" {
		return "", false
	}

	return value, true
}
