package development

import (
	"database/sql"
	"git.markbailey.dev/cervers/ptpp/lib/logger"
	"git.markbailey.dev/cervers/ptpp/lib/repository"
	"git.markbailey.dev/cervers/ptpp/models/sqlite"
	_ "github.com/mattn/go-sqlite3"
	"sync"
)

var (
	tDB         *sql.DB
	tDBLock     = &sync.Mutex{}
	TestQueries *sqlite.Queries
)

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

func NewTestDB(l logger.ILogger) (*DB, error) {
	if tDB == nil {
		tDBLock.Lock()
		defer tDBLock.Unlock()
		db, err := sql.Open("sqlite3", "data/database.db")
		if err != nil {
			l.Error(l.Wrap(err, "Error opening database connection"))
			return nil, err
		}
		tDB = db
	}

	if TestQueries == nil {
		TestQueries = sqlite.New(tDB)
	}

	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 SQLite3 database"))
}
