package bootstrapimpl

import (
	"testing"

	"github.com/nexuscrm/kernel/pkg/schema"
	"github.com/nexuscrm/shared/pkg/constants"
)

// syntheticDefs builds a minimal []schema.TableDefinition slice for tests that
// do not want to touch the real system_tables.json.
func syntheticDefs(entries []struct {
	name    string
	ttype   string
	rwperm  string
	kprefix string
}) []schema.TableDefinition {
	out := make([]schema.TableDefinition, 0, len(entries))
	for _, e := range entries {
		out = append(out, schema.TableDefinition{
			TableName:               e.name,
			TableType:               e.ttype,
			RequiredWritePermission: e.rwperm,
			KeyPrefix:               e.kprefix,
		})
	}
	return out
}

// TestAssertKeyPrefixCleanSubstrate verifies that a fully-covered,
// uniqueness-clean set of system_core definitions produces zero violations.
func TestAssertKeyPrefixCleanSubstrate(t *testing.T) {
	defs := syntheticDefs([]struct {
		name    string
		ttype   string
		rwperm  string
		kprefix string
	}{
		{"Account", "system_core", "ModifyAllData", "001"},
		{"Contact", "system_core", "ModifyAllData", "003"},
		{"User", "system_core", "ManageUsers", "005"},
	})

	result := &AssertionResult{}
	assertWritableSystemCoreTablesHaveKeyPrefix(defs, result)

	if len(result.Violations) != 0 {
		t.Fatalf("expected 0 violations, got %d: %+v", len(result.Violations), result.Violations)
	}
}

// TestAssertKeyPrefixCoverageViolation verifies that a writable system_core
// entry with an empty keyPrefix produces exactly one SeverityWarning violation.
func TestAssertKeyPrefixCoverageViolation(t *testing.T) {
	defs := syntheticDefs([]struct {
		name    string
		ttype   string
		rwperm  string
		kprefix string
	}{
		{"Account", "system_core", "ModifyAllData", "001"},
		{"Contact", "system_core", "ManageUsers", ""}, // missing keyPrefix
	})

	result := &AssertionResult{}
	assertWritableSystemCoreTablesHaveKeyPrefix(defs, result)

	if len(result.Violations) != 1 {
		t.Fatalf("expected 1 violation, got %d: %+v", len(result.Violations), result.Violations)
	}
	v := result.Violations[0]
	if v.Severity != constants.SeverityWarning {
		t.Fatalf("expected SeverityWarning, got %q", v.Severity)
	}
	if v.Object != "Contact" {
		t.Fatalf("expected offender=Contact, got %q", v.Object)
	}
}

// TestAssertKeyPrefixUniquenessViolation verifies that two entries sharing the
// same non-empty keyPrefix produce exactly one SeverityError violation.
func TestAssertKeyPrefixUniquenessViolation(t *testing.T) {
	defs := syntheticDefs([]struct {
		name    string
		ttype   string
		rwperm  string
		kprefix string
	}{
		{"Account", "system_core", "ModifyAllData", "001"},
		{"AnotherTable", "system_core", "ModifyAllData", "001"}, // duplicate prefix
	})

	result := &AssertionResult{}
	assertWritableSystemCoreTablesHaveKeyPrefix(defs, result)

	var errorViolations []AssertionViolation
	for _, v := range result.Violations {
		if v.Severity == constants.SeverityError {
			errorViolations = append(errorViolations, v)
		}
	}
	if len(errorViolations) != 1 {
		t.Fatalf("expected 1 SeverityError violation, got %d: %+v", len(errorViolations), result.Violations)
	}
	if errorViolations[0].Object != "AnotherTable" {
		t.Fatalf("expected offender=AnotherTable, got %q", errorViolations[0].Object)
	}
}

// TestAssertKeyPrefixBlockedExempt verifies that a BLOCKED system_core entry
// with an empty keyPrefix is exempt from the coverage check.
func TestAssertKeyPrefixBlockedExempt(t *testing.T) {
	defs := syntheticDefs([]struct {
		name    string
		ttype   string
		rwperm  string
		kprefix string
	}{
		{"_System_Session", "system_core", "BLOCKED", ""},      // exempt
		{"_System_LoginHistory", "system_core", "BLOCKED", ""}, // exempt
		{"User", "system_core", "ManageUsers", "005"},
	})

	result := &AssertionResult{}
	assertWritableSystemCoreTablesHaveKeyPrefix(defs, result)

	if len(result.Violations) != 0 {
		t.Fatalf("expected 0 violations (BLOCKED entries are exempt), got %d: %+v", len(result.Violations), result.Violations)
	}
}

// TestAssertKeyPrefixNonSystemCoreExempt verifies that non-system_core entries
// (e.g. system_metadata, custom_object) with empty keyPrefix are not flagged.
func TestAssertKeyPrefixNonSystemCoreExempt(t *testing.T) {
	defs := syntheticDefs([]struct {
		name    string
		ttype   string
		rwperm  string
		kprefix string
	}{
		{"_System_Object", "system_metadata", "", ""},     // not system_core
		{"Lead__c", "custom_object", "ModifyAllData", ""}, // not system_core
		{"User", "system_core", "ManageUsers", "005"},
	})

	result := &AssertionResult{}
	assertWritableSystemCoreTablesHaveKeyPrefix(defs, result)

	if len(result.Violations) != 0 {
		t.Fatalf("expected 0 violations (non-system_core entries exempt), got %d: %+v", len(result.Violations), result.Violations)
	}
}

// TestAssertKeyPrefixRegressionRealJSON is the parity regression test (per Round 0
// ssot-invariants.md). It calls assertWritableSystemCoreTablesHaveKeyPrefix with
// the real committed system_tables.json and asserts zero SeverityError violations.
//
// SeverityWarning violations (coverage gaps) are expected and logged — the
// assertion issues warnings for the ~14 named-permission system_core entries
// that currently lack keyPrefixes; those are being filled in progressively.
// Only SeverityError (uniqueness violation) would block server startup.
func TestAssertKeyPrefixRegressionRealJSON(t *testing.T) {
	defs := GetSystemTableDefinitions()

	result := &AssertionResult{}
	assertWritableSystemCoreTablesHaveKeyPrefix(defs, result)

	var errs []AssertionViolation
	for _, v := range result.Violations {
		if v.Severity == constants.SeverityError {
			errs = append(errs, v)
		}
	}
	if len(errs) > 0 {
		t.Fatalf("real system_tables.json has %d keyPrefix uniqueness error(s) — "+
			"no two system_tables entries may share a keyPrefix value: %+v", len(errs), errs)
	}
	// Log coverage warnings for visibility without failing the test.
	var warns []AssertionViolation
	for _, v := range result.Violations {
		if v.Severity == constants.SeverityWarning {
			warns = append(warns, v)
		}
	}
	if len(warns) > 0 {
		t.Logf("coverage warnings (%d): writable system_core entries without keyPrefix "+
			"(progressive fill-in tracked by follow-up work):", len(warns))
		for _, w := range warns {
			t.Logf("  - %s: %s", w.Object, w.Description)
		}
	}
}
