package database

import (
	"fmt"
	"strings"
	"time"

	"gitlab.com/mbugroup/lti-api.git/internal/config"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func Connect(dbHost, dbName string) *gorm.DB {
	parts := []string{
		fmt.Sprintf("host=%s", dbHost),
		fmt.Sprintf("user=%s", config.DBUser),
		fmt.Sprintf("password=%s", config.DBPassword),
		fmt.Sprintf("dbname=%s", dbName),
		fmt.Sprintf("port=%d", config.DBPort),
		fmt.Sprintf("sslmode=%s", config.DBSSLMode),
		"TimeZone=Asia/Shanghai",
	}
	if config.DBSSLRootCert != "" {
		parts = append(parts, fmt.Sprintf("sslrootcert=%s", config.DBSSLRootCert))
	}
	if config.DBSSLCert != "" {
		parts = append(parts, fmt.Sprintf("sslcert=%s", config.DBSSLCert))
	}
	if config.DBSSLKey != "" {
		parts = append(parts, fmt.Sprintf("sslkey=%s", config.DBSSLKey))
	}
	dsn := strings.Join(parts, " ")

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
		Logger:                 logger.Default.LogMode(logger.Info),
		SkipDefaultTransaction: true,
		PrepareStmt:            false,
		TranslateError:         true,
	})
	if err != nil {
		utils.Log.Errorf("Failed to connect to database: %+v", err)
	}

	sqlDB, errDB := db.DB()
	if errDB != nil {
		utils.Log.Errorf("Failed to connect to database: %+v", errDB)
	}

	// Config connection pooling
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(60 * time.Minute)

	return db
}
