package db

import (
	"apskel-pos-be/config"
	"fmt"

	_ "github.com/lib/pq"
	"go.uber.org/zap"
	_ "gopkg.in/yaml.v3"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func NewPostgres(c config.Database) (*gorm.DB, error) {
	dialector := postgres.New(postgres.Config{
		DSN: c.DSN(),
	})

	db, err := gorm.Open(dialector, &gorm.Config{})

	if err != nil {
		return nil, err
	}

	zapCfg := zap.NewProductionConfig()
	zapCfg.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
	zapCfg.DisableCaller = false

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}
	if err := sqlDB.Ping(); err != nil {
		return nil, err
	}

	sqlDB.SetMaxIdleConns(c.MaxIdleConnectionsInSecond)
	sqlDB.SetMaxOpenConns(c.MaxOpenConnectionsInSecond)
	sqlDB.SetConnMaxLifetime(c.ConnectionMaxLifetime())

	fmt.Println("Successfully connected to PostgreSQL database")

	return db, nil
}
