package sfcrmappservice

import (
	"context"
	"encoding/json"
	"net/url"
	"strings"
	"testing"

	querycodec "github.com/pingcap-inc/nexuscrm-app-packs/sfcrm/querycodec"
	semantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/queryv1"
)

func TestSelectionFailurePreservedThroughRuntimeTransportAndHTTP(t *testing.T) {
	client := queryResponseTransport(t, semantic.Response{}, &semantic.Failure{Category: semantic.FailureInvalidRequest, InvalidComponent: semantic.InvalidComponentSelection})
	calls := 0
	h, err := NewRuntimeQueryHandler(func(ctx context.Context, _ string, req semantic.Request) (semantic.Response, error) {
		calls++
		return client.QueryRecords(ctx, req)
	}, func(context.Context, string, semantic.HistoryRequest) (semantic.HistoryResponse, error) {
		t.Fatal("unexpected history query")
		return semantic.HistoryResponse{}, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	result := h.Handle(queryDateTestContext(t), querycodec.Request{Route: querycodec.Route{Kind: querycodec.RouteQuery, Version: "v63.0"}, Query: url.Values{"q": {"SELECT Id, Missing FROM Item LIMIT 1"}}})
	body, err := json.Marshal(result.Body)
	if err != nil || result.Status != 400 || calls != 1 || !strings.Contains(string(body), `"errorCode":"INVALID_FIELD"`) {
		t.Fatalf("calls=%d status=%d body=%s err=%v", calls, result.Status, body, err)
	}
}
