package tests

import (
	"fmt"
	"testing"
	"time"

	"nex/backend/internal/config"

	"github.com/stretchr/testify/require"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func SetupTestDB(t *testing.T) *gorm.DB {
	t.Helper()

	db, err := gorm.Open(sqlite.Open(":memory:?_foreign_keys=on"), &gorm.Config{})
	require.NoError(t, err, "failed to open test database")

	sqlDB, err := db.DB()
	require.NoError(t, err, "failed to get underlying sql.DB")
	sqlDB.SetMaxOpenConns(1)
	sqlDB.SetConnMaxLifetime(0)

	err = db.AutoMigrate(&config.Provider{}, &config.Model{}, &config.UsageStats{})
	require.NoError(t, err, "failed to auto-migrate test database")

	return db
}

func CleanupTestDB(t *testing.T, db *gorm.DB) {
	t.Helper()

	time.Sleep(50 * time.Millisecond)

	sqlDB, err := db.DB()
	require.NoError(t, err, "failed to get underlying sql.DB")

	err = sqlDB.Close()
	require.NoError(t, err, "failed to close test database")
}

func CreateTestProvider(t *testing.T, db *gorm.DB, id string) config.Provider {
	t.Helper()

	provider := config.Provider{
		ID:      id,
		Name:    fmt.Sprintf("test-provider-%s", id),
		APIKey:  fmt.Sprintf("test-api-key-%s", id),
		BaseURL: fmt.Sprintf("https://api.test-%s.com", id),
		Enabled: true,
	}

	err := db.Create(&provider).Error
	require.NoError(t, err, "failed to create test provider")

	return provider
}

func CreateTestModel(t *testing.T, db *gorm.DB, id string, providerID string, modelName string) (config.Model, error) {
	t.Helper()

	model := config.Model{
		ID:         id,
		ProviderID: providerID,
		ModelName:  modelName,
		Enabled:    true,
	}

	err := db.Create(&model).Error
	return model, err
}
