package db

import (
	"<@var(context.project.goprefix)>/<@var(context.project.name)>/config"
	"github.com/amacneil/dbmate/v2/pkg/dbmate"
	_ "github.com/amacneil/dbmate/v2/pkg/driver/postgres"
	"log"
	"net/url"
	"strconv"
	"strings"
)

var Q *Queries

func RunDbMigrations() error {

	err := config.Load()
	if err != nil {
		return err
	}
	conf := *config.Conf
	dbUrl, err := url.Parse(strings.Join([]string{
		"postgresql://",
		conf.Database.User,
		":",
		conf.Database.Password,
		"@",
		conf.Database.Host,
		":",
		strconv.Itoa(conf.Database.Port),
		"/",
		conf.Database.Name,
	}, ""))
	if err != nil {
		return err
	}
	db := dbmate.New(dbUrl)
	db.FS = MigrationsFs
	db.MigrationsDir = []string{"migrations"}
	migrations, err := db.FindMigrations()
	if err != nil {
		return err
	}
	for _, m := range migrations {
		log.Default().Println(m.Version, m.FilePath)
	}
	db.AutoDumpSchema = false
	log.Default().Println("\nApplying...")
	err = db.CreateAndMigrate()
	if err != nil {
		log.Default().Println(err.Error())
	}
	err = db.DumpSchema()
	if err != nil {
		return err
	}

	return nil

}
