package onboarding

import (
	"testing"

	"qctextbuilder/internal/qcclient"
)

func TestDetectFieldKind(t *testing.T) {
	tests := []struct {
		name   string
		path   string
		sample string
		want   string
	}{
		{
			name:   "exact image token",
			path:   "hero.image",
			sample: "#IMAGE#",
			want:   "image",
		},
		{
			name:   "image placeholder bracketed",
			path:   "gallery.galleryImage_m4178_15",
			sample: "[image image image image]",
			want:   "image",
		},
		{
			name:   "image path hint even with text sample",
			path:   "section.thumbnailUrl",
			sample: "headline",
			want:   "image",
		},
		{
			name:   "empty sample is unknown",
			path:   "hero.title",
			sample: "",
			want:   "unknown",
		},
		{
			name:   "plain text field",
			path:   "hero.title",
			sample: "This is a headline",
			want:   "text",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := detectFieldKind(tt.path, tt.sample)
			if got != tt.want {
				t.Fatalf("detectFieldKind() = %q, want %q", got, tt.want)
			}
		})
	}
}

func TestFlattenDiscovery_DisablesImageLikeFields(t *testing.T) {
	data := qcclient.GenerateContentData{
		"gallery": {
			"galleryImage_m4178_15": "[image image image image]",
		},
		"hero": {
			"title": "Welcome",
		},
	}

	fields := flattenDiscovery(99, "manifest-1", data)
	if len(fields) != 2 {
		t.Fatalf("flattenDiscovery() field count = %d, want 2", len(fields))
	}

	byPath := map[string]string{}
	enabled := map[string]bool{}
	websiteSections := map[string]string{}
	for _, f := range fields {
		byPath[f.Path] = f.FieldKind
		enabled[f.Path] = f.IsEnabled
		websiteSections[f.Path] = f.WebsiteSection
	}

	imagePath := "gallery.galleryImage_m4178_15"
	if byPath[imagePath] != "image" {
		t.Fatalf("field %s kind = %q, want image", imagePath, byPath[imagePath])
	}
	if enabled[imagePath] {
		t.Fatalf("field %s should be disabled by default", imagePath)
	}
	if websiteSections[imagePath] != "gallery" {
		t.Fatalf("field %s websiteSection = %q, want gallery", imagePath, websiteSections[imagePath])
	}

	textPath := "hero.title"
	if byPath[textPath] != "text" {
		t.Fatalf("field %s kind = %q, want text", textPath, byPath[textPath])
	}
	if !enabled[textPath] {
		t.Fatalf("field %s should be enabled by default", textPath)
	}
	if websiteSections[textPath] != "hero" {
		t.Fatalf("field %s websiteSection = %q, want hero", textPath, websiteSections[textPath])
	}
}
