package nextcloud

import "testing"

func TestUserIDFromClaimsPrefersEmail(t *testing.T) {
	got := UserIDFromClaims("User@Example.com", "opaque-sub")
	if got != "user@example.com" {
		t.Fatalf("UserIDFromClaims() = %q", got)
	}
}

func TestUserIDFromClaimsFallbackSub(t *testing.T) {
	got := UserIDFromClaims("", "opaque-sub")
	if got != "opaque-sub" {
		t.Fatalf("UserIDFromClaims() = %q", got)
	}
}

func TestNormalizeDAVHref(t *testing.T) {
	tests := []struct {
		in, want string
	}{
		{
			"/cloud/remote.php/dav/addressbooks/users/alice/contacts/",
			"/remote.php/dav/addressbooks/users/alice/contacts/",
		},
		{
			"cloud/remote.php/dav/addressbooks/users/alice/contacts/uid.vcf",
			"/remote.php/dav/addressbooks/users/alice/contacts/uid.vcf",
		},
		{
			"/remote.php/dav/addressbooks/users/alice/contacts/uid.vcf",
			"/remote.php/dav/addressbooks/users/alice/contacts/uid.vcf",
		},
	}
	for _, tc := range tests {
		got := normalizeDAVHref(tc.in)
		if got != tc.want {
			t.Fatalf("normalizeDAVHref(%q) = %q, want %q", tc.in, got, tc.want)
		}
	}
}

func TestDavResponseErrorNotFound(t *testing.T) {
	raw := []byte(`<?xml version="1.0"?><d:error xmlns:d="DAV:"><d:message>missing</d:message></d:error>`)
	if err := davResponseError(raw, 404); err != ErrPrincipalNotFound {
		t.Fatalf("davResponseError() = %v", err)
	}
}

func TestGenerateNextcloudPassword(t *testing.T) {
	pw, err := generateNextcloudPassword()
	if err != nil {
		t.Fatal(err)
	}
	if len(pw) < 24 {
		t.Fatalf("password too short: %d", len(pw))
	}
}
