package database

import (
	"context"
	"os"
	"testing"

	"github.com/Xe/uuid"
)

const (
	cryptoKey    = `I7EzBRcoFtbW6RuqKdFjxYTHC_bpQLPJO3zyS2R-sf8=`
	certNameBase = "cert."
	certValue    = "hunter2"
)

func testCerts(ctx context.Context, t *testing.T, c Certs) {
	cn := certNameBase + uuid.New()

	t.Run("put", func(t *testing.T) {
		data := certValue + uuid.New()

		err := c.Put(ctx, cn, []byte(data))
		if err != nil {
			t.Fatal(err)
		}

		data2, err := c.Get(ctx, cn)
		if err != nil {
			t.Fatal(err)
		}

		if data != string(data2) {
			t.Fatalf("expected data to be %q, got %q", data, string(data2))
		}
	})

	t.Run("get", func(t *testing.T) {
		_, err := c.Get(ctx, cn)
		if err != nil {
			t.Fatal(err)
		}
	})

	t.Run("delete", func(t *testing.T) {
		err := c.Delete(ctx, cn)
		if err != nil {
			t.Fatal(err)
		}

		_, err = c.Get(ctx, cn)
		if err == nil {
			t.Fatal("able to fetch a deleted item")
		}
	})
}

func TestBoltDBCertStorage(t *testing.T) {
	st, p, ctx, cancel := newTestBoltStorage(t)
	defer os.RemoveAll(p)
	defer st.Close()
	defer cancel()

	testCerts(ctx, t, st.Certs())
}
