package admin

import (
	"bytes"
	"crypto/rand"
	"testing"
)

func TestPasswordHashVerify(t *testing.T) {
	hash, err := HashPassword("correct horse battery staple")
	if err != nil {
		t.Fatal(err)
	}
	if !VerifyPassword(hash, "correct horse battery staple") {
		t.Error("valid password rejected")
	}
	if VerifyPassword(hash, "wrong password") {
		t.Error("wrong password accepted")
	}
	if VerifyPassword("not-a-phc-string", "x") {
		t.Error("malformed hash accepted")
	}
	// Two hashes of the same password must differ (random salt).
	hash2, _ := HashPassword("correct horse battery staple")
	if hash == hash2 {
		t.Error("identical hashes for same password — salt not applied")
	}
}

func TestEncryptDecryptSecret(t *testing.T) {
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		t.Fatal(err)
	}
	const plain = "JBSWY3DPEHPK3PXP"
	blob, err := EncryptSecret(key, plain)
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Contains(blob, []byte(plain)) {
		t.Error("ciphertext contains plaintext secret")
	}
	got, err := DecryptSecret(key, blob)
	if err != nil {
		t.Fatal(err)
	}
	if got != plain {
		t.Errorf("DecryptSecret = %q; want %q", got, plain)
	}

	// Wrong key must fail.
	badKey := make([]byte, 32)
	if _, err := DecryptSecret(badKey, blob); err == nil {
		t.Error("decrypt with wrong key succeeded")
	}
	// Short key rejected.
	if _, err := EncryptSecret(key[:16], plain); err == nil {
		t.Error("encrypt accepted 16-byte key")
	}
}
