package bootstrapimpl

import (
	"testing"

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

func TestConnectorIngressReceiptSystemTable(t *testing.T) {
	defs := GetManagedTableDefinitions()
	def, ok := findConnectorIngressReceiptTableForTest(defs, "_System_ConnectorIngressReceipt")
	if !ok {
		t.Fatalf("_System_ConnectorIngressReceipt not found in system_tables.json")
	}
	if def.TableType != "system_core" || def.Category != "integration" {
		t.Fatalf("table type/category = %q/%q, want system_core/integration", def.TableType, def.Category)
	}
	if def.RequiredReadPermission != "BLOCKED" || def.RequiredWritePermission != "BLOCKED" {
		t.Fatalf("permissions = %q/%q, want BLOCKED/BLOCKED", def.RequiredReadPermission, def.RequiredWritePermission)
	}

	columns := make(map[string]schema.ColumnDefinition, len(def.Columns))
	for _, col := range def.Columns {
		columns[col.Name] = col
	}
	for _, name := range []string{
		"Id", "Namespace", "InstalledPackId", "PackVersion", "SecretName", "SecretAlgorithm",
		"VerifierCapabilityKind", "ParserCapabilityKind", "RequestMethod", "RequestTargetHash", "RequestTargetCiphertext",
		"ReceiptKey", "BodyHash", "BodyCiphertext", "AllowedHeadersCiphertext", "Status", "AttemptCount",
		"NextAttemptAt", "ClaimedBy", "ClaimToken", "ClaimedAt", "LeaseExpiresAt",
		"EnqueuedEventIds", "EnqueueMetadata", "LastError", "LastErrorAt", "PurgeAfter",
	} {
		if _, ok := columns[name]; !ok {
			t.Fatalf("missing column %s", name)
		}
	}
	for _, name := range []string{"RequestTargetCiphertext", "BodyCiphertext", "AllowedHeadersCiphertext"} {
		if got := columns[name].Type; got != "LONGTEXT" {
			t.Fatalf("%s type = %q, want LONGTEXT", name, got)
		}
		if columns[name].Nullable {
			t.Fatalf("%s nullable = true, want false", name)
		}
	}
	if got := columns["RequestTargetHash"].Type; got != "VARCHAR(64)" {
		t.Fatalf("RequestTargetHash type = %q, want VARCHAR(64)", got)
	}

	indexes := make(map[string]schema.IndexDefinition, len(def.Indices))
	for _, idx := range def.Indices {
		indexes[idx.Name] = idx
	}
	receiptKey, ok := indexes["uniq_connector_ingress_receipt_key"]
	if !ok {
		t.Fatalf("missing uniq_connector_ingress_receipt_key")
	}
	if !receiptKey.Unique || len(receiptKey.Columns) != 1 || receiptKey.Columns[0] != "ReceiptKey" {
		t.Fatalf("receipt key index = %+v, want unique ReceiptKey", receiptKey)
	}
	if _, ok := indexes["idx_connector_ingress_receipt_claim"]; !ok {
		t.Fatalf("missing claim index")
	}
	if _, ok := indexes["idx_connector_ingress_receipt_purge"]; !ok {
		t.Fatalf("missing purge index")
	}
}

func findConnectorIngressReceiptTableForTest(defs []schema.TableDefinition, tableName string) (schema.TableDefinition, bool) {
	for _, def := range defs {
		if def.TableName == tableName {
			return def, true
		}
	}
	return schema.TableDefinition{}, false
}
