package layoutroutingsecurity

import (
	"context"
	"database/sql"
	"errors"
	"strings"
	"testing"
)

func TestShadowDDLIsMigrationOnlyAndHasNoSecondSelector(t *testing.T) {
	combined := shadowStateTableDDL + "\n" + shadowAttestationTableDDL
	for _, forbidden := range []string{
		"INSERT ", "UPDATE ", "DELETE ", "DROP ", "RENAME ",
		"MAX(", "IsCurrent", "idx_latest",
	} {
		if strings.Contains(combined, forbidden) {
			t.Fatalf("shadow DDL contains forbidden %q", forbidden)
		}
	}
	for _, required := range []string{
		"CREATE TABLE IF NOT EXISTS " + shadowStateTableName,
		"CREATE TABLE IF NOT EXISTS " + shadowAttestationTableName,
		"PRIMARY KEY (OrgId)",
		"PRIMARY KEY (OrgId, SecurityEpoch)",
		"LayoutRoutingSecurityViewDigest VARCHAR(71) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL",
	} {
		if !strings.Contains(combined, required) {
			t.Fatalf("shadow DDL is missing %q", required)
		}
	}
	if strings.Count(combined, "DEFAULT CURRENT_TIMESTAMP(6)") != 4 {
		t.Fatalf("temporal default count = %d, want 4", strings.Count(combined, "DEFAULT CURRENT_TIMESTAMP(6)"))
	}
}

func TestShadowViewStoreDDLIsMigrationOnlyAndHasNoSelector(t *testing.T) {
	for _, forbidden := range []string{
		"INSERT ", "UPDATE ", "DELETE ", "DROP ", "RENAME ",
		"MAX(", "SecurityEpoch", "IsCurrent", "idx_latest",
	} {
		if strings.Contains(shadowViewStoreTableDDL, forbidden) {
			t.Fatalf("shadow view-store DDL contains forbidden %q", forbidden)
		}
	}
	for _, required := range []string{
		"CREATE TABLE IF NOT EXISTS " + shadowViewStoreTableName,
		"CanonicalViewBytes LONGBLOB NOT NULL",
		"PRIMARY KEY (OrgId, LayoutRoutingSecurityViewDigest)",
	} {
		if !strings.Contains(shadowViewStoreTableDDL, required) {
			t.Fatalf("shadow view-store DDL is missing %q", required)
		}
	}
	if strings.Count(shadowViewStoreTableDDL, "DEFAULT CURRENT_TIMESTAMP(6)") != 2 {
		t.Fatalf("temporal default count = %d, want 2", strings.Count(shadowViewStoreTableDDL, "DEFAULT CURRENT_TIMESTAMP(6)"))
	}
}

func TestNilDatabaseAndUnverifiedOrMixedHandlesFailClosed(t *testing.T) {
	for name, verify := range map[string]func(context.Context, *sql.DB) (*VerifiedTables, error){
		"create shadow": CreateHaltedShadow,
		"verify shadow": VerifyShadow,
		"verify live":   VerifyLive,
	} {
		if tables, err := verify(context.Background(), nil); err == nil || tables != nil {
			t.Fatalf("%s nil database = (%#v, %v)", name, tables, err)
		}
	}
	for name, tables := range map[string]*VerifiedTables{
		"nil":  nil,
		"zero": {},
		"mixed": {
			db:          &sql.DB{},
			state:       liveStateTableIdentity,
			attestation: shadowAttestationTableIdentity,
		},
	} {
		if _, _, _, err := requireVerifiedTables(tables); !errors.Is(err, ErrSchema) {
			t.Fatalf("%s handle error = %v, want ErrSchema", name, err)
		}
	}
}

func TestViewStoreVerificationRejectsNilDatabase(t *testing.T) {
	for name, verify := range map[string]func(context.Context, *sql.DB) (*VerifiedViewStore, error){
		"create shadow": CreateHaltedShadowViewStore,
		"verify shadow": VerifyShadowViewStore,
		"verify live":   VerifyLiveViewStore,
	} {
		if store, err := verify(context.Background(), nil); err == nil || store != nil {
			t.Fatalf("%s nil database = (%#v, %v)", name, store, err)
		}
	}
}

func mutateColumns(columns []columnShape, mutate func([]columnShape)) []columnShape {
	result := append([]columnShape(nil), columns...)
	mutate(result)
	return result
}
