package main

import (
	// External
	"github.com/jackc/pgx/v5/pgxpool"
	"smon/dbschema"

	// Standard
	"context"
	"fmt"
)

var (
	db *pgxpool.Pool
)

func initDb(host string, port int, name, username, password string) (err error) {
	logger.Info("database", "host", host, "port", port, "name", name, "username", username)

	// The main database connection is configured.
	connString := fmt.Sprintf(
		"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		host,
		port,
		username,
		password,
		name,
	)
	db, err = pgxpool.New(context.Background(), connString)

	// The schema upgrader keeps track of the SQL schema version and
	// runs SQL scripts to upgrade it if necessary.
	upgrader := dbschema.NewUpgrader()
	upgrader.SetLogCallback(sqlLogCallback)
	upgrader.SetSqlCallback(sqlSourceCallback)

	_, err = upgrader.AddDatabaseInstance(db, config.Database.Name)
	if err != nil {
		return
	}

	err = upgrader.Run()
	return
}

func sqlLogCallback(op, msg string) {
	logger.Info("dbschema", "op", op, "message", msg)
}

func sqlSourceCallback(dbName string, version int) ([]byte, bool) {
	fname := fmt.Sprintf("sql/%05d.sql", version)
	data, err := sqlFS.ReadFile(fname)
	if err != nil {
		return []byte{}, false
	}
	return data, true
}
