package auth

import (
	"path/filepath"
	"testing"
)

func TestTokenStore(t *testing.T) {
	store, err := NewTokenStore(filepath.Join(t.TempDir(), "tokens.db"))
	if err != nil {
		t.Fatal(err)
	}
	defer store.Close()

	raw, err := store.Create("dash")
	if err != nil {
		t.Fatal(err)
	}
	if len(raw) < 36 || raw[:4] != "nad_" {
		t.Fatalf("token %q lacks %q prefix or is too short", raw, "nad_")
	}

	// Round-trip: the minted secret resolves to its name.
	if name, ok := store.Lookup(raw); !ok || name != "dash" {
		t.Errorf("Lookup(valid) = %q,%v; want dash,true", name, ok)
	}
	// A wrong secret (and a non-prefixed one) must not resolve.
	if _, ok := store.Lookup("nad_wrong"); ok {
		t.Error("Lookup(wrong) succeeded")
	}
	if _, ok := store.Lookup("no-prefix"); ok {
		t.Error("Lookup(no prefix) succeeded")
	}
	// Duplicate name is rejected.
	if _, err := store.Create("dash"); err == nil {
		t.Error("Create duplicate name succeeded; want error")
	}
	// Revocation is immediate.
	if err := store.Delete("dash"); err != nil {
		t.Fatal(err)
	}
	if _, ok := store.Lookup(raw); ok {
		t.Error("Lookup after Delete succeeded")
	}
}
