package analytics

import (
	"context"
	"testing"

	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
	"github.com/nexuscrm/shared/pkg/queryspec"
)

func TestQueryParentLikeComposesWithRootPredicate(t *testing.T) {
	for _, op := range []string{"like", "not like"} {
		t.Run(op, func(t *testing.T) {
			repo := &clauseFLSRepository{}
			qs := parentFilterQueryService(repo, parentFilterRootSchema(
				models.FieldMetadata{APIName: "StageName", Type: constants.FieldTypeString},
				models.FieldMetadata{APIName: "AccountId", Type: constants.FieldTypeReference, ReferenceTo: []string{"Account"}},
			), parentFilterAccountSchema(models.FieldMetadata{APIName: "Industry", Type: constants.FieldTypeString}))
			predicate := queryspec.Or(
				queryspec.ComparisonPredicate(queryspec.FieldOperand("StageName"), "like", queryspec.LiteralOperand("%Probe%")),
				queryspec.ComparisonPredicate(queryspec.FieldOperand("Account.Industry"), op, queryspec.LiteralOperand("%Tech_%")),
			)
			_, err := qs.QueryWithSpec(context.Background(), queryspec.QuerySpec{ObjectAPIName: "Opportunity", SelectFields: []string{constants.FieldID}, Filter: predicate}, &models.UserSession{ID: "005-reader", ProfileID: "00e-standard"})
			if err != nil {
				t.Fatalf("composite parent LIKE rejected: %v", err)
			}
			if !repo.findCalled {
				t.Fatal("query did not reach repository")
			}
			assertParentFilterPlan(t, repo.findReq.ParentFilterPaths, *defaultParentFilterPlan("Account.Industry", "Account", "AccountId", "Account", "Industry"))
		})
	}
}

func TestQueryParentLikeRejectsComputedOrNonliteralOperands(t *testing.T) {
	for _, expr := range []string{
		"__NCRM_QUERY_LIKE__(Account.Industry, StageName)",
		"__NCRM_QUERY_LIKE__(Account.Industry, 42)",
		"__NCRM_QUERY_LIKE__(LOWER(Account.Industry), '%tech%')",
		"__NCRM_QUERY_LIKE__(Account.Industry, '%tech%', 'extra')",
	} {
		t.Run(expr, func(t *testing.T) {
			repo := &clauseFLSRepository{}
			qs := parentFilterQueryService(repo, parentFilterRootSchema(
				models.FieldMetadata{APIName: "StageName", Type: constants.FieldTypeString},
				models.FieldMetadata{APIName: "AccountId", Type: constants.FieldTypeReference, ReferenceTo: []string{"Account"}},
			), parentFilterAccountSchema(models.FieldMetadata{APIName: "Industry", Type: constants.FieldTypeString}))
			_, err := qs.QueryWithSpec(context.Background(), queryspec.QuerySpec{ObjectAPIName: "Opportunity", SelectFields: []string{constants.FieldID}, Filter: queryspec.FormulaPredicate(expr)}, &models.UserSession{ID: "005-reader", ProfileID: "00e-standard"})
			if err == nil || repo.findCalled {
				t.Fatalf("unsupported parent expression reached execution: %v", err)
			}
		})
	}
}
