package database

import (
	"fmt"
	"log"
	"os"

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

var PostgresDatabase *gorm.DB

func getDSN() string {
	user := os.Getenv("PSQL_USER")
	password := os.Getenv("PSQL_PASS")
	database := os.Getenv("PSQL_NAME")
	host, exists := os.LookupEnv("PSQL_HOST")
	if !exists {
		host = "localhost"
	}
	return fmt.Sprintf("postgresql://%s:%s@%s/%s?sslmode=disable", user, password, host, database)
}

func ConnectPostgres() {
	var err error
	PostgresDatabase, err = gorm.Open(postgres.Open(getDSN()), new(gorm.Config))
	if err != nil {
		log.Fatalln(err)
	}
}
