// Copyright (C) 2023 Marius Schellenberger

package db

import (
	"git.giftfish.de/ston1th/keyctl/pkg/core"
	"git.giftfish.de/ston1th/keyctl/pkg/key"
)

const keyPrefix = "key/"

func (db *DB) GetKeys() (keys core.Keys, err error) {
	err = db.store.ForEachPrefix(keyPrefix, func(k string, _ []byte) error {
		key, err := db.GetKey(k)
		if err == nil {
			keys = append(keys, key)
		}
		return nil
	})
	return
}

func (db *DB) GetKey(id string) (k core.Key, err error) {
	k, err = db.GetKeyWithSecret(id)
	k.Key = ""
	return
}

func (db *DB) GetKeyWithSecret(id string) (k core.Key, err error) {
	err = db.store.Get(keyPrefix+id, &k)
	return
}

func (db *DB) CreateKey(name, existing string, size int, enc core.Encoding, t core.Type) (k core.Key, err error) {
	kstore, k, err := key.Generate(name, existing, size, enc, t)
	if err != nil {
		return
	}
	err = db.store.Set(keyPrefix+k.ID, &kstore)
	return
}

func (db *DB) DeleteKey(id string) error {
	return db.store.Delete(keyPrefix + id)
}
