package sfcrmappservice

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"github.com/pingcap-inc/nexuscrm-api-host/runtimegrpc"
	semantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/queryv1"
)

func TestIncompleteDateLocatorFailsBeforeCalendarDependencies(t *testing.T) {
	// No metadata port: malformed cursors must be rejected before calendar lookup,
	// instead of becoming either a dependency failure or a fresh query.
	service, err := NewService(ServiceConfig{
		RuntimeEvaluate: (&fakeRuntime{}).Evaluate,
		RuntimeQuery: func(context.Context, string, semantic.Request) (semantic.Response, error) {
			t.Fatal("invalid cursor executed Runtime query")
			return semantic.Response{}, nil
		},
		RuntimeHistoryQuery: func(context.Context, string, semantic.HistoryRequest) (semantic.HistoryResponse, error) {
			t.Fatal("unexpected history")
			return semantic.HistoryResponse{}, nil
		},
		RuntimeReady: func() bool { return true }, RuntimeMetrics: func() runtimegrpc.RuntimeClientMetrics { return runtimegrpc.RuntimeClientMetrics{} }, RequestTimeout: 5 * time.Second, MaxRequestBytes: 65536,
	})
	if err != nil {
		t.Fatal(err)
	}
	for _, anchor := range []any{nil, map[string]any{"instant": "2026-09-08T00:30:00Z", "timeZone": ""}, map[string]any{"timeZone": "UTC"}} {
		data, err := json.Marshal(map[string]any{"q": url.QueryEscape("SELECT Id FROM Item WHERE Due = TODAY"), "limit": 200, "offset": 200, "dateAnchor": anchor})
		if err != nil {
			t.Fatal(err)
		}
		req := httptest.NewRequest(http.MethodGet, "/services/data/v63.0/query/"+base64.URLEncoding.EncodeToString(data), nil)
		req.Header.Set("Authorization", "Bearer test-token")
		out := httptest.NewRecorder()
		service.ServeHTTP(out, req)
		if out.Code != 400 || !strings.Contains(out.Body.String(), `"errorCode":"INVALID_QUERY_LOCATOR"`) {
			t.Fatalf("status=%d body=%s", out.Code, out.Body.String())
		}
	}
}
