package production

import (
	"database/sql"
	"git.markbailey.dev/cervers/ptpp/lib/logger"
	"git.markbailey.dev/cervers/ptpp/lib/repository"
	"git.markbailey.dev/cervers/ptpp/models/postgres"
	_ "github.com/lib/pq"
	"os"
	"sync"
)

var (
	prodDB      *sql.DB
	prodDBLock  = &sync.Mutex{}
	ProdQueries *postgres.Queries
)

type DB struct {
	logger     logger.ILogger
	Repository repository.IRepository
}

func NewProdDB(l logger.ILogger) (*DB, error) {
	if prodDB == nil {
		prodDBLock.Lock()
		defer prodDBLock.Unlock()
		db, err := sql.Open("postgres", os.Getenv("DB_URL"))
		if err != nil {
			l.Error(l.Wrap(err, "Error opening database connection"))
			return nil, err
		}
		prodDB = db
	}

	if ProdQueries == nil {
		ProdQueries = postgres.New(prodDB)
	}

	return &DB{
		logger:     l,
		Repository: &Repo{},
	}, nil
}

func (d DB) Repo() repository.IRepository {
	return d.Repository
}

func (d DB) Info(msg string) {
	d.logger.Info(msg)
}

func (d DB) Warn(msg string) {
	d.logger.Warn(msg)
}

func (d DB) Error(err error) {
	d.logger.Error(d.logger.Wrap(err, "Error in Postgresql database"))
}
