package bootstrap

import (
	"encoding/json"
	"os"
	"testing"
)

// TestSystemTableParity ensures that all critical System Tables defined in code/constants
// are present in the system_tables.json source of truth.
// This prevents "Ghost Table" bugs where code expects a table that Bootstrap doesn't create.
func TestSystemTableParity(t *testing.T) {
	// 1. Load system_tables.json
	data, err := os.ReadFile("system_tables.json")
	if err != nil {
		t.Fatalf("Failed to read system_tables.json: %v", err)
	}

	var definitions []struct {
		TableName string `json:"tableName"`
	}
	if err := json.Unmarshal(data, &definitions); err != nil {
		t.Fatalf("Failed to parse system_tables.json: %v", err)
	}

	// Index definitions for O(1) lookup
	definedTables := make(map[string]bool)
	for _, def := range definitions {
		definedTables[def.TableName] = true
	}

	// 2. Define Critical Tables (The "Must Haves")
	// These are tables that our code (Models, Repositories) explicitly relies on.
	requiredTables := []string{
		"_System_Object",
		"_System_Field",
		"_System_Table", // The Meta-Metadata Registry
		"Profile",
		"UserRole",
		"User",
		"_System_App",
		"_System_PageLayout",     // Critical for UI
		"_System_ValidationRule", // Critical for Logic
		"_System_Action",         // Critical for Buttons
		"FlowDefinition",         // Critical for Automation (Salesforce-compatible)
		"Flow",                   // Critical for Automation (Salesforce-compatible)
		"FlowInterview",          // Critical for Automation (Salesforce-compatible)
		"SharingRule",            // Critical for Security
		"Dashboard",
		"DashboardComponent",
		"Report",
	}

	// 3. Assert Existence
	for _, req := range requiredTables {
		if !definedTables[req] {
			t.Errorf("CRITICAL: Required system table '%s' is MISSING from system_tables.json. Bootstrap will fail to create it, causing runtime crashes.", req)
		}
	}
}
