// Copyright (C) 2023 Marius Schellenberger

package db

import (
	"io"
	"path/filepath"

	"git.giftfish.de/ston1th/godrop/v2"
	"git.giftfish.de/ston1th/keyctl/pkg/store"
	"github.com/go-logr/logr"
)

const storeFile = "store.db"

type DB struct {
	log   logr.Logger
	store store.Store
}

func NewPlain(log logr.Logger, dir string) (db *DB, err error) {
	db = &DB{log: log}
	dbFile := filepath.Join(dir, storeFile)
	err = godrop.Unveil(dbFile, "rwc")
	if err != nil {
		return
	}
	db.store, err = store.NewBoltStore(dbFile, nil)
	return
}

func New(log logr.Logger, dir string) (db *DB, err error) {
	db, err = NewPlain(log, dir)
	if err != nil {
		return
	}

	err = db.RunMigrations()
	return
}

func (db *DB) Dump(w io.Writer) error {
	return db.store.Dump(w)
}

func (db *DB) Restore(r io.Reader) error {
	return db.store.Restore(r)
}

func (db *DB) Close() error {
	return db.store.Close()
}
