package data

import (
	"testing"

	"kra/pkg/database/migration"
)

func TestMigrateAllRunsModuleSchemasWithoutBootstrapSeed(t *testing.T) {
	db, err := openWithDriver("sqlite", "file:"+t.Name()+"?mode=memory&cache=shared")
	if err != nil {
		t.Fatal(err)
	}
	if err = migrateAll(db); err != nil {
		t.Fatal(err)
	}
	if err = migrateAll(db); err != nil {
		t.Fatalf("second migration run: %v", err)
	}
	for _, table := range []string{"sys_integration_configs", "sys_users", "sys_base_menus", "pay_orders"} {
		if !db.Migrator().HasTable(table) {
			t.Fatalf("migration did not create %s", table)
		}
	}
	var versions int64
	if err = db.Table(migration.TableName).Count(&versions).Error; err != nil {
		t.Fatal(err)
	}
	if versions != 6 {
		t.Fatalf("migration versions = %d, want 6", versions)
	}
	var communicationRows []integrationConfigPO
	if err = db.Where("kind IN ?", []string{"mq", "websocket"}).Order("kind, provider").Find(&communicationRows).Error; err != nil {
		t.Fatal(err)
	}
	if len(communicationRows) != 3 {
		t.Fatalf("communication integration rows = %d, want 3", len(communicationRows))
	}
	for _, row := range communicationRows {
		if row.Enabled || row.Config == "" {
			t.Fatalf("default communication integration = %#v", row)
		}
	}
	for _, table := range []string{"sys_users", "sys_base_menus", "sys_apis"} {
		var count int64
		if err = db.Table(table).Count(&count).Error; err != nil {
			t.Fatal(err)
		}
		if count != 0 {
			t.Fatalf("migration seeded %s: rows=%d", table, count)
		}
	}
}
