package dialectsfcrm

import (
	"context"
	"net/http"
	"reflect"
	"testing"

	"github.com/nexuscrm/shared/pkg/contract"
	"github.com/nexuscrm/shared/pkg/dialect"
	"github.com/nexuscrm/shared/pkg/models"
)

func TestLayoutHistoryBindingPreservesPhysicalDescribeAuthorization(t *testing.T) {
	for _, tc := range []struct{ name, parent string }{
		{"Accounthistory", "Account"}, {"accounthistory", "account"}, {"ACCOUNTHISTORY", "ACCOUNT"}, {"OPPORTUNITYFIELDHISTORY", "Opportunity"}, {"Delivery__history", "Delivery__c"},
	} {
		name := tc.name
		t.Run(name, func(t *testing.T) {
			parent := historyDescribeTestAccount()
			parent.APIName = tc.parent
			parentAlias := tc.parent
			metadata := &fakeDescribeMetadata{schemas: map[string]*models.ObjectMetadata{parentAlias: &parent, name: {APIName: name}}}
			parentAccess := &contract.EffectiveObjectAccess{Object: contract.ObjectAccess{Read: true}, Fields: map[string]contract.FieldAccess{"Name": {Readable: true}}}
			policy := &fakeDescribePolicy{access: map[string]*contract.EffectiveObjectAccess{parentAlias: parentAccess, name: {Object: contract.ObjectAccess{Read: false}}}}
			response, err := DescribeObjectNeutralHandler(context.Background(), &dialect.Request{Version: "v63.0", Params: map[string]string{"sobject": name}}, dialectDescribeDeps(metadata, policy))
			if err != nil || response.Status != http.StatusForbidden || !reflect.DeepEqual(policy.fullSeen, []string{name}) {
				t.Fatalf("status=%d err=%v permission targets=%v", response.Status, err, policy.fullSeen)
			}
			if access := uiAPIFieldHistoryAccess(parentAlias, parentAccess, name); access != nil {
				t.Fatalf("ordinary object borrowed parent history access: %#v", access)
			}
		})
	}
}
