package crud

import (
	"strings"
	"testing"

	"aijianzhan/platform/internal/blueprint"
	"aijianzhan/platform/internal/meta"
)

func TestValidateFiltersWhitelist(t *testing.T) {
	ref := &meta.ResourceRef{
		Resource: blueprint.APIResource{
			List: &blueprint.ListOpt{AllowedFilters: []string{"name"}},
		},
	}
	if err := validateFilters(ref, map[string]string{"hack": "1"}); err == nil {
		t.Fatal("expected rejection")
	}
	if err := validateFilters(ref, map[string]string{"name": "a"}); err != nil {
		t.Fatal(err)
	}
}

func TestSanitizeRejectsUnknown(t *testing.T) {
	n := false
	entity := blueprint.Entity{
		Name: "item", Table: "item", PrimaryKey: "id",
		Fields: []blueprint.Field{
			{Name: "id", Type: "bigint"},
			{Name: "name", Type: "string", Nullable: &n},
		},
	}
	_, err := sanitizeBody(entity, map[string]any{"name": "x", "drop": "1"}, false)
	if err == nil || !strings.Contains(err.Error(), "unknown field") {
		t.Fatalf("expected unknown field, got %v", err)
	}
}

func TestQualifiedTable(t *testing.T) {
	ref := &meta.ResourceRef{
		App:    &meta.AppRecord{SchemaName: "app_t1_demo"},
		Entity: blueprint.Entity{Table: "item"},
	}
	got := qualifiedTable(ref)
	want := `"app_t1_demo"."item"`
	if got != want {
		t.Fatalf("got %s want %s", got, want)
	}
}
