package testutils

import (
	"testing"
	"time"

	"veza-backend-api/internal/database"
)

// SetupBenchmarkDB configure une DB pour benchmarks (T0044)
func SetupBenchmarkDB(b *testing.B) *database.Database {
	dbURL := GetTestDatabaseURL()
	dbConfig := &database.Config{
		URL:          dbURL,
		MaxOpenConns: 10,
		MaxIdleConns: 5,
		MaxLifetime:  5 * time.Minute,
		MaxIdleTime:  1 * time.Minute,
	}

	db, err := database.NewDatabase(dbConfig)
	if err != nil {
		b.Fatalf("Failed to setup benchmark database: %v", err)
	}

	b.Cleanup(func() {
		if err := db.Close(); err != nil {
			b.Logf("Error closing database: %v", err)
		}
	})

	return db
}

// RunBenchmarkWithSetup exécute un benchmark avec setup/teardown (T0044)
func RunBenchmarkWithSetup(b *testing.B, setup func(*testing.B) interface{}, benchFunc func(*testing.B, interface{}), teardown func(*testing.B, interface{})) {
	setupResult := setup(b)

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			benchFunc(b, setupResult)
		}
	})

	if teardown != nil {
		teardown(b, setupResult)
	}
}

// BenchmarkExample exemple de benchmark (T0044)
func BenchmarkExample(b *testing.B) {
	setup := SetupBenchmarkDB(b)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// Code à benchmarker
		_ = setup
	}
}
