package database

import (
	"os"
	"testing"

	"github.com/Xe/uuid"
	"golang.org/x/net/context"
)

const (
	creator  = "shachi"
	hostBase = "shachi.loves."
)

func testRoutes(ctx context.Context, t *testing.T, r Routes) {
	hostname := hostBase + uuid.New()
	id := uuid.New()

	t.Run("put", func(t *testing.T) {
		rt := Route{
			ID:       id,
			Creator:  creator,
			Hostname: hostname,
		}

		_, err := r.Put(ctx, rt)
		if err != nil {
			t.Fatal(err)
		}
	})

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

	t.Run("getHost", func(t *testing.T) {
		_, err := r.GetHost(ctx, hostname)
		if err != nil {
			t.Fatal(err)
		}
	})

	t.Run("getAll", func(t *testing.T) {
		res, err := r.GetAll(ctx, creator)
		if err != nil {
			t.Fatal(err)
		}
		if len(res) == 0 {
			t.Fatal("didn't get any routes back for shachi")
		}
	})

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

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

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

	testRoutes(ctx, t, st.Routes())
}

func TestPostgresRouteStorage(t *testing.T) {
	st, ctx, cancel := newTestPostgresStorage(t, os.Getenv("DATABASE_URL"))
	defer st.Close()
	defer cancel()

	testRoutes(ctx, t, st.Routes())
}
