package migration

import (
	"context"
	"net/http"
	"strings"
	"testing"
)

func TestListGoogleCalendarCancelledEvent(t *testing.T) {
	client := mockGoogleHTTPClient(t, func(w http.ResponseWriter, r *http.Request) {
		if strings.Contains(r.URL.Path, "/calendar/v3/calendars/") {
			_, _ = w.Write([]byte(`{
				"items":[{"id":"e1","status":"cancelled","summary":"gone"}],
				"nextSyncToken":"sync-1"
			}`))
			return
		}
		http.NotFound(w, r)
	})

	c := NewCalendarImporter(nil, nil).WithHTTPClient(client)
	events, _, syncToken, err := c.listSourceEvents(
		context.Background(),
		"token",
		"google",
		sourceCalendar{ID: "primary"},
		"",
		"sync-old",
	)
	if err != nil {
		t.Fatalf("list events: %v", err)
	}
	if len(events) != 1 || !events[0].Deleted {
		t.Fatalf("events: %#v", events)
	}
	if syncToken != "sync-1" {
		t.Fatalf("sync token = %q", syncToken)
	}
}

func TestListMicrosoftCalendarDeltaRemoved(t *testing.T) {
	client := mockGraphHTTPClient(t, func(w http.ResponseWriter, r *http.Request) {
		if strings.Contains(r.URL.Path, "/events/delta") {
			_, _ = w.Write([]byte(`{
				"value":[{"id":"e1","@removed":{"reason":"deleted"}}],
				"@odata.deltaLink":"https://graph.microsoft.com/delta/next"
			}`))
			return
		}
		http.NotFound(w, r)
	})

	c := NewCalendarImporter(nil, nil).WithHTTPClient(client)
	events, next, err := c.listMicrosoftCalendarDelta(
		context.Background(),
		"token",
		"cal-1",
		"https://graph.microsoft.com/v1.0/me/calendars/cal-1/events/delta",
	)
	if err != nil {
		t.Fatalf("list delta: %v", err)
	}
	if len(events) != 1 || !events[0].Deleted {
		t.Fatalf("events: %#v", events)
	}
	if next == "" {
		t.Fatal("expected next cursor")
	}
}
