package postgres

import (
	"database/sql"
	"fmt"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// PostgresOpen connects to a PostgreSQL server and returns a *sql.DB.
// sslmode defaults to "disable" when empty.
// Constructs a DSN of the form:
//
//	host=<host> port=<port> user=<user> password=<password> dbname=<dbname> sslmode=<sslmode>
func PostgresOpen(host string, port int, user, password, dbname string, sslmode string) (*sql.DB, error) {
	if sslmode == "" {
		sslmode = "disable"
	}
	dsn := fmt.Sprintf(
		"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
		host, port, user, password, dbname, sslmode,
	)
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		return nil, fmt.Errorf("postgres_open: open: %w", err)
	}
	if err := db.Ping(); err != nil {
		db.Close()
		return nil, fmt.Errorf("postgres_open: ping %s:%d/%s: %w", host, port, dbname, err)
	}
	return db, nil
}
