package data

import (
	"testing"

	bizpayment "kra/internal/biz/payment"
	dataintegration "kra/internal/data/integration"
	"kra/internal/modules"
	"kra/pkg/database/migration"
	platformmodule "kra/pkg/module"
)

func testCatalog() platformmodule.Catalog {
	return modules.Catalog()
}

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, testCatalog()); err != nil {
		t.Fatal(err)
	}
	if err = migrateAll(db, testCatalog()); 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 != 8 {
		t.Fatalf("migration versions = %d, want 8", versions)
	}
	var communicationRows []dataintegration.ConfigPO
	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))
	}
	var paymentRows int64
	if err = db.Model(&dataintegration.ConfigPO{}).Where("kind = ?", "payment").Count(&paymentRows).Error; err != nil {
		t.Fatal(err)
	}
	if paymentRows != int64(len(bizpayment.SupportedPaymentProviders)) {
		t.Fatalf("payment integration rows = %d, want %d", paymentRows, len(bizpayment.SupportedPaymentProviders))
	}
	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)
		}
	}
}
