package secret

import "testing"

func TestEncryptRoundTrip(t *testing.T) {
	salt, _ := NewSalt()
	key, err := DeriveKey("correct horse battery staple", salt)
	if err != nil {
		t.Fatalf("derive: %v", err)
	}
	c, err := New(key)
	if err != nil {
		t.Fatalf("new: %v", err)
	}
	for _, plain := range []string{"", "hunter2", "pâßwörd 🔐", "a-very-long-tqsl-private-key-password-1234567890"} {
		enc := c.Encrypt(plain)
		if !IsEncrypted(enc) {
			t.Fatalf("Encrypt(%q) not prefixed: %q", plain, enc)
		}
		got, err := c.Decrypt(enc)
		if err != nil || got != plain {
			t.Errorf("round trip %q: got %q err %v", plain, got, err)
		}
	}
}

func TestDecryptPlaintextPassthrough(t *testing.T) {
	salt, _ := NewSalt()
	key, _ := DeriveKey("pw", salt)
	c, _ := New(key)
	// A legacy (un-prefixed) value must come back unchanged.
	if got, err := c.Decrypt("plain-password"); err != nil || got != "plain-password" {
		t.Errorf("passthrough: got %q err %v", got, err)
	}
}

func TestWrongPassphraseFailsVerifier(t *testing.T) {
	salt, _ := NewSalt()
	good, _ := DeriveKey("right", salt)
	gc, _ := New(good)
	v := gc.MakeVerifier()
	if !gc.CheckVerifier(v) {
		t.Fatal("correct passphrase should pass the verifier")
	}
	bad, _ := DeriveKey("wrong", salt)
	bc, _ := New(bad)
	if bc.CheckVerifier(v) {
		t.Fatal("wrong passphrase must NOT pass the verifier")
	}
	// And a tampered ciphertext must not decrypt.
	if _, err := gc.Decrypt(Prefix + "AAAA"); err == nil {
		t.Error("forged ciphertext decrypted without error")
	}
}
