package database

import (
	"os"
	"testing"

	"golang.org/x/net/context"
)

func testTokens(ctx context.Context, t *testing.T, tk Tokens) {
	var (
		tokenID   string
		tokenBody string
	)

	t.Run("put", func(t *testing.T) {
		tok := Token{
			Owner: creator,
		}

		tok2, err := tk.Put(ctx, tok)
		if err != nil {
			t.Fatal(err)
		}

		tokenID = tok2.ID
		tokenBody = tok2.Body
	})

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

	t.Run("getBody", func(t *testing.T) {
		_, err := tk.GetBody(ctx, tokenBody)
		if err != nil {
			t.Fatal(err)
		}
	})

	t.Run("getAll", func(t *testing.T) {
		lis, err := tk.GetAll(ctx, creator)
		if err != nil {
			t.Fatal(err)
		}
		if len(lis) == 0 {
			t.Fatal("expected results but got none")
		}
	})

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

		_, err = tk.Get(ctx, tokenID)
		if err == nil {
			t.Fatal("can fetch a deleted resource")
		}
	})
}

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

	testTokens(ctx, t, st.Tokens())
}
