// Copyright (C) 2023 Marius Schellenberger

package db

import (
	"errors"

	"git.giftfish.de/ston1th/keyctl/pkg/store"
)

const (
	versionKey     = "version/version"
	currentVersion = 0
)

type migrator func(*DB, int) error

var migrators = []migrator{
	func(_ *DB, _ int) error {
		return nil
	},
}

func (db *DB) RunMigrations() (err error) {
	log := db.log.WithName("migration")
	var version int
	err = db.store.Get(versionKey, &version)
	if err == store.ErrKeyNotFound {
		err = db.store.Set(versionKey, currentVersion)
		if err != nil {
			return
		}
		err = db.store.Get(versionKey, &version)
		if err != nil {
			return
		}
	}
	log.Info("db versions", "current", version, "new", currentVersion)
	if currentVersion < version {
		return errors.New("incompatible versions")
	}
	if currentVersion == version {
		log.Info("nothing to do")
	}
	for version < currentVersion {
		v := version + 1
		log.Info("running", "version", v)
		err = migrators[v](db, v)
		if err != nil {
			return
		}
		err = db.store.Set(versionKey, v)
		if err != nil {
			return
		}
		version = v
		log.Info("finished", "version", v)
	}
	return
}
