package migration

import (
	"strings"
	"testing"
)

func TestAdminConsentURL(t *testing.T) {
	svc := NewOAuthService(OAuthConfig{
		MicrosoftClientID:  "client-id",
		MicrosoftSecret:    "secret",
		MicrosoftTenant:    "contoso.onmicrosoft.com",
		RedirectURL:        "https://suite.example.com/api/v1/migration/oauth/callback",
	}, nil)
	url, err := svc.AdminConsentURL("", EncodeAdminConsentState("550e8400-e29b-41d4-a716-446655440000"))
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(url, "adminconsent") {
		t.Fatalf("expected adminconsent url, got %q", url)
	}
	if !strings.Contains(url, "client-id") {
		t.Fatalf("missing client id: %q", url)
	}
	if !strings.Contains(url, "state=project%3A") {
		t.Fatalf("missing project state: %q", url)
	}
}

func TestAdminConsentURLWithoutState(t *testing.T) {
	svc := NewOAuthService(OAuthConfig{
		MicrosoftClientID: "client-id",
		MicrosoftSecret:   "secret",
		RedirectURL:       "https://suite.example.com/api/v1/migration/oauth/callback",
	}, nil)
	url, err := svc.AdminConsentURL("contoso.onmicrosoft.com", "")
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(url, "state=") {
		t.Fatalf("unexpected state in url: %q", url)
	}
}

func TestSanitizeMigrationUID(t *testing.T) {
	uid := sanitizeMigrationUID("google", "people/abc123")
	if uid != "google-people-abc123@ultimail.migrated" {
		t.Fatalf("got %q", uid)
	}
}

func TestParseFlexibleTime(t *testing.T) {
	tm := parseFlexibleTime("2024-05-01T10:00:00Z", "")
	if tm.IsZero() {
		t.Fatal("expected datetime parse")
	}
	tm = parseFlexibleTime("", "2024-05-01")
	if tm.IsZero() {
		t.Fatal("expected date parse")
	}
}
