package controlplane

import (
	"strings"
	"testing"
)

func TestTenantApplyStaysOutOfOperationsGodFile(t *testing.T) {
	operationsSrc := readControlplaneSourceForStructure(t, "operations.go")
	tenantSrc := readControlplaneSourceForStructure(t, "operations_tenant_apply.go")

	for _, symbol := range []string{
		"const TenantOverlayDirEnv",
		"const TenantOverlayRepairLegacyUniqueDuplicatesEnv",
		"func ApplyTenant(",
		"func ApplyTenantWithOptions(",
		"func applyTenantUnlocked(",
	} {
		if strings.Contains(operationsSrc, symbol) {
			t.Fatalf("operations.go still owns tenant apply symbol %q", symbol)
		}
		if !strings.Contains(tenantSrc, symbol) {
			t.Fatalf("operations_tenant_apply.go is missing tenant apply symbol %q", symbol)
		}
	}
	if !strings.Contains(tenantSrc, "pack.Apply(ctx, r.PackDepsWithOptions(options))") {
		t.Fatal("tenant apply must pass ApplyTenantWithOptions options into pack ApplyDeps")
	}

	for _, symbol := range []string{
		"func runInsertRulesValidators(",
		"func engineOwnedByObjectFromAutoNumber(",
	} {
		if !strings.Contains(operationsSrc, symbol) {
			t.Fatalf("operations.go should retain generic validator symbol %q", symbol)
		}
		if strings.Contains(tenantSrc, symbol) {
			t.Fatalf("tenant apply file should not own generic validator symbol %q", symbol)
		}
	}
}

func TestApplyTenantOptionsFromEnvEnablesUniqueRepair(t *testing.T) {
	t.Setenv(TenantOverlayRepairLegacyUniqueDuplicatesEnv, "true")
	options := applyTenantOptionsFromEnv()
	if !options.RepairLegacyUniqueDuplicates {
		t.Fatal("tenant unique duplicate repair option was not enabled from env")
	}
}
