package main

import (
	"encoding/hex"
	"path/filepath"
	"testing"

	cs "fn-registry/functions/cybersecurity"

	"github.com/enmanuel/unibus/pkg/membership"
)

// TestStoreHolderFailClosed: an empty holder denies everything (the bootstrap
// window before the store is set), and starts serving once a store is published.
func TestStoreHolderFailClosed(t *testing.T) {
	h := &storeHolder{}

	// Empty: deny + error (fail closed).
	if h.IsAuthorized("anything") {
		t.Fatalf("empty holder must deny IsAuthorized")
	}
	if _, err := h.subjectACL("anything"); err == nil {
		t.Fatalf("empty holder must error from subjectACL (fail closed)")
	}

	// After set: serves from the real store.
	store, err := membership.Open(filepath.Join(t.TempDir(), "unibus.db"))
	if err != nil {
		t.Fatalf("store: %v", err)
	}
	t.Cleanup(func() { store.Close() })
	id, err := cs.GenerateIdentity()
	if err != nil {
		t.Fatalf("identity: %v", err)
	}
	pub := hex.EncodeToString(id.SignPub)
	if err := store.AddUser(pub, "alice", membership.RoleMember); err != nil {
		t.Fatalf("add user: %v", err)
	}
	h.set(store)

	if !h.IsAuthorized(pub) {
		t.Fatalf("after set, an active user must be authorized")
	}
	if _, err := h.subjectACL(pub); err != nil {
		t.Fatalf("after set, subjectACL must succeed: %v", err)
	}
	if h.IsAuthorized("deadbeef") {
		t.Fatalf("a non-user must not be authorized")
	}
}
