package database

import (
	"path/filepath"
	"testing"

	"nex/backend/internal/config"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap"
)

func TestInit_SQLite(t *testing.T) {
	dir := t.TempDir()
	cfg := &config.DatabaseConfig{
		Driver:          "sqlite",
		Path:            filepath.Join(dir, "test.db"),
		MaxIdleConns:    5,
		MaxOpenConns:    10,
		ConnMaxLifetime: 0,
	}

	zapLogger := zap.NewNop()
	db, err := Init(cfg, zapLogger)
	require.NoError(t, err)
	require.NotNil(t, db)
	defer Close(db)

	sqlDB, err := db.DB()
	require.NoError(t, err)
	require.NotNil(t, sqlDB)
}

func TestClose(t *testing.T) {
	dir := t.TempDir()
	cfg := &config.DatabaseConfig{
		Driver:          "sqlite",
		Path:            filepath.Join(dir, "test.db"),
		MaxIdleConns:    5,
		MaxOpenConns:    10,
		ConnMaxLifetime: 0,
	}

	zapLogger := zap.NewNop()
	db, err := Init(cfg, zapLogger)
	require.NoError(t, err)
	require.NotNil(t, db)

	Close(db)
}

func TestBuildDSN(t *testing.T) {
	cfg := &config.DatabaseConfig{
		Driver:   "mysql",
		Host:     "db.example.com",
		Port:     3306,
		User:     "nexuser",
		Password: "secretpass",
		DBName:   "nexdb",
	}

	dsn := BuildDSN(cfg)
	assert.Equal(t, "nexuser:secretpass@tcp(db.example.com:3306)/nexdb?charset=utf8mb4&parseTime=true&loc=Local", dsn)
}

func TestBuildDSN_EmptyPassword(t *testing.T) {
	cfg := &config.DatabaseConfig{
		Driver: "mysql",
		Host:   "localhost",
		Port:   3306,
		User:   "root",
		DBName: "nex",
	}

	dsn := BuildDSN(cfg)
	assert.Equal(t, "root:@tcp(localhost:3306)/nex?charset=utf8mb4&parseTime=true&loc=Local", dsn)
}
