package db

import (
	"context"
	"database/sql"
	"fmt"
	_ "github.com/lib/pq"
	"os"
	"pgm/data"
	"pgm/logger"
)

func DbConn(c data.HostDetails) *sql.DB {
	var h string
	var u string
	var pw string
	var dbn string
	var psqlInfo string
	h = c.Hostname
	u = c.Username
	pw = c.Secret
	dbn = c.DatabaseName
	psqlInfo = fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		h, 5432, u, pw, dbn)
	db, err := sql.Open("postgres", psqlInfo)
	testUserName := data.ViperReturnKey("test_user")
	logger.Logger("[LOG] reserved username is " + testUserName)
	if err != nil {
		switch u {
		case testUserName:
			logger.Logger("[ERROR] go tests expects to connect with the docker compose database." +
				"[ERROR] run \"docker-compose up\" and re-run tests")
			os.Exit(1)
		default:
			logger.Logger("[ERROR] db error: " + err.Error())
		}

	}

	ctx := context.Background()
	err = db.PingContext(ctx)
	if err != nil {
		switch u {
		case testUserName:
			logger.Logger("[ERROR] db error, unable to ping: " + err.Error()+
				"[ERROR] ensure docker database is running and re-run tests")
			os.Exit(1)
		default:
			logger.Logger("[ERROR] db error: " + err.Error())
		}
	}

	return db
}
