package database

import (
	"os"
	"testing"

	"juhe-factory/api/internal/config"
)

type autoMigrateProbe struct {
	ID uint `gorm:"primaryKey"`
}

func (autoMigrateProbe) TableName() string { return "auto_migrate_probe" }

func TestBootstrapEmptyDatabase(t *testing.T) {
	databaseURL := os.Getenv("JCF_BOOTSTRAP_TEST_DATABASE_URL")
	if databaseURL == "" {
		t.Skip("JCF_BOOTSTRAP_TEST_DATABASE_URL is not configured")
	}

	db, sqlDB, err := Open(config.Config{DatabaseURL: databaseURL})
	if err != nil {
		t.Fatalf("open empty database: %v", err)
	}
	defer sqlDB.Close()

	var tableCount int64
	if err := db.Raw(`SELECT count(*) FROM pg_tables WHERE schemaname = 'public'`).Scan(&tableCount).Error; err != nil {
		t.Fatalf("count initialized tables: %v", err)
	}
	if tableCount != 33 {
		t.Fatalf("expected 33 initialized tables, got %d", tableCount)
	}

	var migrationCount int64
	if err := db.Table("jcf_schema_migrations").Count(&migrationCount).Error; err != nil {
		t.Fatalf("count baseline migrations: %v", err)
	}
	if migrationCount != 0 {
		t.Fatalf("expected no baseline migrations, got %d", migrationCount)
	}

	if err := autoMigrateMissingTables(db, &autoMigrateProbe{}); err != nil {
		t.Fatalf("auto migrate missing table: %v", err)
	}
	if !db.Migrator().HasTable(&autoMigrateProbe{}) {
		t.Fatal("expected AutoMigrate to create missing model table")
	}
	if err := db.Migrator().DropTable(&autoMigrateProbe{}); err != nil {
		t.Fatalf("drop AutoMigrate probe table: %v", err)
	}

	_, reopenedSQLDB, err := Open(config.Config{DatabaseURL: databaseURL})
	if err != nil {
		t.Fatalf("reopen initialized database: %v", err)
	}
	defer reopenedSQLDB.Close()
}
