package torchwood_test

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

	"filippo.io/torchwood"
	"golang.org/x/mod/sumdb/note"
)

func TestSignerRoundtrip(t *testing.T) {
	_, k, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	s, err := torchwood.NewCosignatureSigner("example.com", k)
	if err != nil {
		t.Fatal(err)
	}

	msg := "test\n123\nf+7CoKgXKE/tNys9TTXcr/ad6U/K3xvznmzew9y6SP0=\nextension 1\nextension 2\n"
	n, err := note.Sign(&note.Note{Text: msg}, s)
	if err != nil {
		t.Fatal(err)
	}

	if _, err := note.Open(n, note.VerifierList(s.Verifier())); err != nil {
		t.Fatal(err)
	}

	nn := bytes.Replace(n, []byte("extension 2"), []byte("extension X"), 1)
	if _, err := note.Open(nn, note.VerifierList(s.Verifier())); err == nil {
		t.Fatal("expected error verifying modified note, got nil")
	}

	v, err := torchwood.NewCosignatureVerifier(s.Verifier().String())
	if err != nil {
		t.Fatal(err)
	}
	if v.Name() != "example.com" {
		t.Fatalf("verifier name = %q; want %q", v.Name(), "example.com")
	}
	if v.KeyHash() != s.Verifier().KeyHash() {
		t.Fatalf("verifier hash = %d; want %d", v.KeyHash(), s.Verifier().KeyHash())
	}
	if _, err := note.Open(n, note.VerifierList(v)); err != nil {
		t.Fatal(err)
	}
}
