package repository

import (
	"fmt"
	"sync/atomic"
	"testing"

	_ "modernc.org/sqlite" // 纯 Go SQLite，注册 "sqlite" 驱动
	gormsqlite "gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"github.com/user-management-system/internal/domain"
)

var repoDBCounter int64

// openTestDB 为每个测试打开独立的内存数据库（使用 modernc.org/sqlite，无需 CGO）
// 每次调用都生成唯一的 DSN，避免多个测试共用同一内存 DB 导致 index 重复错误
func openTestDB(t *testing.T) *gorm.DB {
	t.Helper()

	id := atomic.AddInt64(&repoDBCounter, 1)
	dsn := fmt.Sprintf("file:repotestdb%d?mode=memory&cache=private", id)

	db, err := gorm.Open(gormsqlite.New(gormsqlite.Config{
		DriverName: "sqlite",
		DSN:        dsn,
	}), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		t.Fatalf("打开测试数据库失败: %v", err)
	}

	tables := []interface{}{
		&domain.User{},
		&domain.Role{},
		&domain.Permission{},
		&domain.UserRole{},
		&domain.RolePermission{},
	}
	if err := db.AutoMigrate(tables...); err != nil {
		t.Fatalf("数据库迁移失败: %v", err)
	}

	return db
}
