package db

import (
	"fmt"

	_ "github.com/lib/pq"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

func Open(dataSourceName string, debug bool) (*xorm.Engine, error) {
	engine, err := xorm.NewEngine("postgres", dataSourceName)
	if err != nil {
		return nil, fmt.Errorf("open db: %w", err)
	}

	if debug {
		engine.SetLogLevel(log.LOG_DEBUG)
	} else {
		engine.SetLogLevel(log.LOG_WARNING)
	}

	engine.SetMaxOpenConns(25)
	engine.SetMaxIdleConns(5)

	if err := engine.Ping(); err != nil {
		return nil, fmt.Errorf("ping db: %w", err)
	}

	return engine, nil
}
