package migration

import (
	"context"
	"testing"
)

func TestGoogleWorkspaceExport(t *testing.T) {
	mime, ext, ok := googleWorkspaceExport("application/vnd.google-apps.document")
	if !ok || ext != ".docx" || mime == "" {
		t.Fatalf("document export: mime=%q ext=%q ok=%v", mime, ext, ok)
	}
	_, _, ok = googleWorkspaceExport("application/vnd.google-apps.folder")
	if ok {
		t.Fatal("folder should not export")
	}
}

func TestDriveExportFileName(t *testing.T) {
	got := driveExportFileName("Report", ".docx")
	if got != "Report.docx" {
		t.Fatalf("got %q", got)
	}
	got = driveExportFileName("Report.docx", ".docx")
	if got != "Report.docx" {
		t.Fatalf("got %q", got)
	}
}

func TestDriveFolderQueue(t *testing.T) {
	cursor := map[string]any{}
	queue := readDriveFolderQueue(cursor, "google")
	if len(queue) != 1 || queue[0].ID != "root" {
		t.Fatalf("default queue: %#v", queue)
	}
	queue = enqueueDriveFolder(queue, driveFolderRef{ID: "abc", Path: "Docs"})
	writeDriveFolderQueue(cursor, queue)
	if len(readDriveFolderQueue(cursor, "google")) != 2 {
		t.Fatal("expected 2 folders in queue")
	}
}

func TestGoogleSlidesPDFExport(t *testing.T) {
	mime, ext, ok := googleSlidesPDFExport("application/vnd.google-apps.presentation")
	if !ok || ext != ".pdf" || mime != "application/pdf" {
		t.Fatalf("slides pdf export: mime=%q ext=%q ok=%v", mime, ext, ok)
	}
	_, _, ok = googleSlidesPDFExport("application/vnd.google-apps.document")
	if ok {
		t.Fatal("document should not have slides pdf export")
	}
}

func TestImportedPathHelpers(t *testing.T) {
	store := NewImportedItemStoreMemory()
	ctx := context.Background()
	if err := store.MarkPath(ctx, "file-1", "Docs/report.docx"); err != nil {
		t.Fatal(err)
	}
	if got := store.Path("file-1"); got != "Docs/report.docx" {
		t.Fatalf("imported path: got %q", got)
	}
	if err := store.Unmark(ctx, "file-1"); err != nil {
		t.Fatal(err)
	}
	if got := store.Path("file-1"); got != "" {
		t.Fatalf("expected empty after unmark, got %q", got)
	}
}

func TestGoogleCalendarCancelledEvent(t *testing.T) {
	ev := googleCalendarEvent{ID: "evt1", Status: "cancelled"}.toSourceEvent("primary")
	if !ev.Deleted {
		t.Fatal("cancelled event should be deleted")
	}
}

func TestGraphCalendarRemovedEvent(t *testing.T) {
	removed := struct {
		Reason string `json:"reason"`
	}{Reason: "deleted"}
	ev := graphCalendarEvent{ID: "evt1", Removed: &removed}.toSourceEvent("cal1")
	if !ev.Deleted {
		t.Fatal("removed event should be deleted")
	}
}

func TestCalendarSyncTokenHelpers(t *testing.T) {
	cursor := map[string]any{}
	setCalendarSyncToken(cursor, "primary", "token-1")
	tokens := calendarSyncTokens(cursor)
	if tokens["primary"] != "token-1" {
		t.Fatalf("got %#v", tokens)
	}
}
