package contacts

import (
	"testing"

	"github.com/ultisuite/ulti-backend/internal/nextcloud"
)

func TestValidateSyncToken(t *testing.T) {
	token, err := validateSyncToken("")
	if err != nil || token != "" {
		t.Fatalf("empty token: got %q err=%v", token, err)
	}
	token, err = validateSyncToken("  http://nc/sync/1  ")
	if err != nil || token != "http://nc/sync/1" {
		t.Fatalf("trimmed token: got %q err=%v", token, err)
	}
	if token, err = validateSyncToken("   "); err != nil || token != "" {
		t.Fatalf("whitespace-only token treated as empty: got %q err=%v", token, err)
	}
	if _, err = validateSyncToken("<bad>"); err == nil {
		t.Fatal("expected invalid token error")
	}
}

func TestValidateCreateContact(t *testing.T) {
	if validateCreateContact(&nextcloud.Contact{FullName: "Ada"}) != nil {
		t.Fatal("expected valid contact")
	}
	if validateCreateContact(&nextcloud.Contact{}) == nil {
		t.Fatal("expected missing full_name error")
	}
}

func TestValidateIfMatch(t *testing.T) {
	if validateIfMatch(`"abc123"`) != nil {
		t.Fatal("expected valid If-Match")
	}
	if validateIfMatch("") == nil {
		t.Fatal("expected missing If-Match error")
	}
	if validateIfMatch(" \t") == nil {
		t.Fatal("expected whitespace-only If-Match error")
	}
	if validateIfMatch("bad\r\nvalue") == nil {
		t.Fatal("expected invalid If-Match error")
	}
}

func TestValidateDeletePath(t *testing.T) {
	if validateDeletePath("/remote.php/dav/addressbooks/users/alice/contacts/uid.vcf") != nil {
		t.Fatal("expected valid path")
	}
	if validateDeletePath("") == nil {
		t.Fatal("expected missing path error")
	}
}

func TestValidateInteractionQuery(t *testing.T) {
	email, limit, err := validateInteractionQuery("ada@example.com", "15")
	if err != nil {
		t.Fatalf("expected valid query, got error: %v", err)
	}
	if email != "ada@example.com" {
		t.Fatalf("unexpected normalized email: %q", email)
	}
	if limit != 15 {
		t.Fatalf("unexpected limit: %d", limit)
	}

	_, _, err = validateInteractionQuery("", "10")
	if err == nil {
		t.Fatal("expected required email error")
	}

	_, _, err = validateInteractionQuery("not-an-email", "")
	if err == nil {
		t.Fatal("expected invalid email error")
	}

	_, _, err = validateInteractionQuery("ada@example.com", "999")
	if err == nil {
		t.Fatal("expected invalid limit error")
	}
}
