// Copyright (C) 2019 Marius Schellenberger

package db

import (
	"git.giftfish.de/ston1th/docstore/pkg/log"
	"git.giftfish.de/ston1th/docstore/pkg/store"
)

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

type migrator func(*DB) (int, error)

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

func (db *DB) RunMigrations() (err error) {
	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.Printf("db: database version %d", version)
	for version < currentVersion {
		v := version + 1
		log.Printf("db: running migration %d", v)
		version, err = migrators[v](db)
		if err != nil {
			return
		}
		err = db.store.Set(versionKey, version)
		if err != nil {
			return
		}
	}
	return
}
