package layoutownership

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestCuratedLayoutOwnershipDataSpecsUseCaseInsensitiveObjectMatching(t *testing.T) {
	root := layoutOwnershipRepoRoot(t)
	specs := []string{
		"data-specs/2026-04-27a-resolve-curated-layout-cutover-ownership.md",
		"data-specs/2026-04-27b-audit-curated-layout-cutover-ownership.md",
	}

	for _, relPath := range specs {
		content, err := os.ReadFile(filepath.Join(root, relPath))
		if err != nil {
			t.Fatalf("read %s: %v", relPath, err)
		}
		text := string(content)
		if !strings.Contains(text, "LOWER(pl.`ObjectApiName`) = LOWER(la.`ObjectApiName`)") {
			t.Fatalf("%s must join PageLayout/ObjectApiName case-insensitively", relPath)
		}
		if !strings.Contains(text, "LOWER(la.`ObjectApiName`) IN ('opportunity', 'user')") {
			t.Fatalf("%s must filter ObjectApiName case-insensitively", relPath)
		}
	}
}

func TestCuratedLayoutOwnershipDataSpecsCoverMissingWildcardState(t *testing.T) {
	root := layoutOwnershipRepoRoot(t)
	specs := []string{
		"data-specs/2026-04-27a-resolve-curated-layout-cutover-ownership.md",
		"data-specs/2026-04-27b-audit-curated-layout-cutover-ownership.md",
	}

	for _, relPath := range specs {
		content, err := os.ReadFile(filepath.Join(root, relPath))
		if err != nil {
			t.Fatalf("read %s: %v", relPath, err)
		}
		text := string(content)
		if !strings.Contains(text, "'missing_wildcard' AS BlockingClass") {
			t.Fatalf("%s must surface live layouts with no wildcard assignment", relPath)
		}
		if !strings.Contains(text, "NOT EXISTS") ||
			!strings.Contains(text, "la.`RoleId` IS NULL") ||
			!strings.Contains(text, "la.`ProfileId` IS NULL") ||
			!strings.Contains(text, "la.`RecordTypeId` IS NULL") {
			t.Fatalf("%s must detect missing wildcard routes through null routing dimensions", relPath)
		}
	}
}

func TestCuratedLayoutOwnershipRunbookUsesIdempotentReviewedWildcardInsert(t *testing.T) {
	root := layoutOwnershipRepoRoot(t)
	relPath := "data-specs/2026-04-27c-apply-curated-layout-cutover.md"
	content, err := os.ReadFile(filepath.Join(root, relPath))
	if err != nil {
		t.Fatalf("read %s: %v", relPath, err)
	}
	text := string(content)
	if !strings.Contains(text, "SELECT\n  ${NewOpportunityAssignmentId}") ||
		!strings.Contains(text, "SELECT\n  ${NewUserAssignmentId}") {
		t.Fatalf("%s must include reviewed wildcard inserts for both curated objects", relPath)
	}
	if !strings.Contains(text, "AND NOT EXISTS") ||
		!strings.Contains(text, "la.`RoleId` IS NULL") ||
		!strings.Contains(text, "la.`ProfileId` IS NULL") ||
		!strings.Contains(text, "la.`RecordTypeId` IS NULL") {
		t.Fatalf("%s must make reviewed wildcard inserts idempotent", relPath)
	}
}
