package identity

import (
	"crypto/ed25519"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"strings"
	"testing"
)

func TestFormatFaceHeader(t *testing.T) {
	header := FormatFaceHeader(strings.Repeat("A", 200))
	for _, line := range strings.Split(header, "\r\n") {
		if len(line) > 76 {
			t.Fatalf("folded line length = %d", len(line))
		}
	}
}

func TestGenerateFaceUsesExistingCLI(t *testing.T) {
	if _, err := FindCLI(); err != nil {
		t.Skip(err)
	}
	value, err := GenerateFace("reader@example.org")
	if err != nil {
		t.Fatal(err)
	}
	if _, err := decodeFacePNG(value); err != nil {
		t.Fatal(err)
	}
}

func TestGenerateVFaceBindsUsernameEmailAndPublicKey(t *testing.T) {
	if _, err := FindCLI(); err != nil {
		t.Skip(err)
	}
	public, _, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	publicKey := base64.StdEncoding.EncodeToString(public)
	profile, err := GenerateVFace("pseudonym", "reader@example.org", publicKey)
	if err != nil {
		t.Fatal(err)
	}
	input := "pseudonym|reader@example.org|" + publicKey
	identityHash := sha256.Sum256([]byte(input))
	if profile.Input != input || profile.IdentityHash != hex.EncodeToString(identityHash[:]) {
		t.Fatalf("unexpected VFace identity: %#v", profile)
	}
	if profile.PNGHash == "" || profile.FaceBase64 == "" {
		t.Fatalf("VFace image metadata is incomplete: %#v", profile)
	}
	headers := strings.Join(profile.Headers(), "\n")
	for _, want := range []string{"X-VFace-Version: 1", "X-Ed25519-Pub: " + publicKey, "Identity-Hash: " + profile.IdentityHash, "X-VFace-Hash: sha256:" + profile.IdentityHash, "X-VFace-Verify: " + VFaceVerificationURL} {
		if !strings.Contains(headers, want) {
			t.Fatalf("VFace headers missing %q: %s", want, headers)
		}
	}
}
