package querycodec

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/url"
	"testing"
)

// Layout binding support must not broaden the query codec's routing grammar.
// These names use ordinary object authorization, not a parent's history access.
func TestLayoutHistoryBindingPreservesOrdinaryQueryRouting(t *testing.T) {
	for _, name := range []string{"Accounthistory", "accounthistory", "ACCOUNTHISTORY", "OPPORTUNITYFIELDHISTORY", "Delivery__history", "OpportunityHistory"} {
		for _, kind := range []RouteKind{RouteQuery, RouteQueryAll, RouteToolingQuery, RouteMore} {
			t.Run(name+"/"+string(kind), func(t *testing.T) {
				queries, histories := 0, 0
				handler := mustHandler(t, Executor{
					Query: func(_ context.Context, r QueryRequest, _ int) (Result, error) {
						queries++
						if r.ObjectAPIName != name {
							t.Fatalf("object=%q", r.ObjectAPIName)
						}
						return Result{}, &Failure{Category: FailureForbidden}
					},
					History: func(context.Context, HistoryRequest) (HistoryResult, error) {
						histories++
						return HistoryResult{Done: true}, nil
					},
				})
				raw := "SELECT Id FROM " + name
				request := Request{Route: Route{Kind: kind, Version: "v63.0"}, Query: url.Values{"q": {raw}}}
				if kind == RouteMore {
					data, _ := json.Marshal(locatorData{Query: url.QueryEscape(raw), Limit: 200})
					request.Route.Locator = base64.URLEncoding.EncodeToString(data)
				}
				response := handler.Handle(context.Background(), request)
				if queries != 1 || histories != 0 || response.Status != http.StatusForbidden {
					t.Fatalf("query=%d history=%d status=%d", queries, histories, response.Status)
				}
			})
		}
	}
}
