package store_test

import (
	"database/sql"
	"os"
	"testing"

	"github.uio.no/torjus/apiary/honeypot/ssh/store"
)

func TestPostgresStore(t *testing.T) {
	var dsn string
	var found bool
	dsn, found = os.LookupEnv("APIARY_TEST_POSTGRES_DSN")
	if !found {
		t.Skipf("APIARY_TEST_POSTGRES_DSN not set. Skipping.")
	}

	dropPGDatabase(dsn)

	s, err := store.NewPostgresStore(dsn)
	if err != nil {
		t.Fatalf("Error getting store: %s", err)
	}

	s.InitDB()

	testLoginAttemptStore(s, t)
}
func TestPostgresStoreWithCache(t *testing.T) {
	var dsn string
	var found bool
	dsn, found = os.LookupEnv("APIARY_TEST_POSTGRES_DSN")
	if !found {
		t.Skipf("APIARY_TEST_POSTGRES_DSN not set. Skipping.")
	}

	dropPGDatabase(dsn)

	pgs, err := store.NewPostgresStore(dsn)
	if err != nil {
		t.Fatalf("Error getting store: %s", err)
	}

	pgs.InitDB()
	s := store.NewCachingStore(pgs)

	testLoginAttemptStore(s, t)
}

func dropPGDatabase(dsn string) {
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		panic(err)
	}

	_, err = db.Exec("DROP TABLE login_attempts")
	if err != nil {
		panic(err)
	}
}
