package database

import (
	"github.com/asdine/storm"
	"golang.org/x/crypto/acme/autocert"
	"golang.org/x/net/context"
)

// Certs is the set of API calls needed to manage certificate resources.
//
// Database backends should implement this interface, they will not need
// to implement certificate decryption, as that will be handled in the layer
// above this DAO.
type Certs interface {
	autocert.Cache

	GetAll(ctx context.Context) ([]CachedCert, error)
}

// CachedCert is an individual cached certificate in the database.
type CachedCert struct {
	Key string `storm:"id"`

	// Encrypted data
	Body []byte // above as a byte slice
}

type storageManager struct {
	Storage
}

func (s *storageManager) Get(ctx context.Context, key string) ([]byte, error) {
	data, err := s.Certs().Get(ctx, key)
	if err != nil {
		if err == storm.ErrNotFound {
			return nil, autocert.ErrCacheMiss
		}

		return nil, err
	}

	return data, nil
}

func (s *storageManager) Put(ctx context.Context, key string, data []byte) error {
	return s.Certs().Put(ctx, key, data)
}

func (s *storageManager) Delete(ctx context.Context, key string) error {
	return s.Certs().Delete(ctx, key)
}

// Cache creates an autocert.Cache from a Storage instance.
func Cache(s Storage) autocert.Cache {
	return autocert.Cache(&storageManager{
		Storage: s,
	})
}
