package secret

import (
	"fmt"

	"github.com/99designs/keyring"
)

const serviceName = "pulsegate"

func OpenKeyring() (keyring.Keyring, error) {
	return keyring.Open(keyring.Config{
		ServiceName: serviceName,
	})
}

func GetPassword(id string) (string, error) {
	kr, err := OpenKeyring()
	if err != nil {
		return "", err
	}

	item, err := kr.Get(id)
	if err != nil {
		return "", err
	}

	return string(item.Data), nil
}

func SavePassword(id string, password string) error {
	if id == "" {
		return fmt.Errorf("password_id fehlt")
	}

	kr, err := OpenKeyring()
	if err != nil {
		return err
	}

	return kr.Set(keyring.Item{
		Key:  id,
		Data: []byte(password),
	})
}