package migration

import (
	"testing"
)

func TestImportedItemStoreStatusMemory(t *testing.T) {
	ctx := t.Context()
	store := NewImportedItemStoreMemory()

	if err := store.MarkImported(ctx, "ok-1"); err != nil {
		t.Fatal(err)
	}
	if !store.Has("ok-1") {
		t.Fatal("expected imported id in done set")
	}

	if err := store.MarkSkipped(ctx, "skip-1", "too large", "big.bin"); err != nil {
		t.Fatal(err)
	}
	if !store.Has("skip-1") {
		t.Fatal("expected skipped id in done set")
	}
	if got := store.Path("skip-1"); got != "big.bin" {
		t.Fatalf("path = %q", got)
	}

	if err := store.MarkFailed(ctx, "fail-1", "upload error", ""); err != nil {
		t.Fatal(err)
	}
	if store.Has("fail-1") {
		t.Fatal("failed item should not be in done set")
	}

	// retry success clears failure
	if err := store.MarkImported(ctx, "fail-1"); err != nil {
		t.Fatal(err)
	}
	if !store.Has("fail-1") {
		t.Fatal("expected retried id in done set")
	}
}

func TestImportedItemStoreMemory(t *testing.T) {
	ctx := t.Context()
	store := NewImportedItemStoreMemory()

	if err := store.MarkPath(ctx, "id-1", "Docs/a.docx"); err != nil {
		t.Fatal(err)
	}
	if !store.Has("id-1") {
		t.Fatal("expected imported id")
	}
	if got := store.Path("id-1"); got != "Docs/a.docx" {
		t.Fatalf("path = %q", got)
	}
	if err := store.Unmark(ctx, "id-1"); err != nil {
		t.Fatal(err)
	}
	if store.Has("id-1") {
		t.Fatal("expected id removed")
	}
}

func TestImportedItemStoreMigratesLegacyCursor(t *testing.T) {
	ctx := t.Context()
	cursor := map[string]any{
		"imported_ids": map[string]any{
			"file-1": true,
		},
		"imported_paths": map[string]any{
			"file-1": "Docs/report.docx",
		},
	}
	store, err := LoadImportedItemStore(ctx, nil, "", cursor)
	if err != nil {
		t.Fatal(err)
	}
	if !store.Has("file-1") {
		t.Fatal("expected migrated id")
	}
	if got := store.Path("file-1"); got != "Docs/report.docx" {
		t.Fatalf("path = %q", got)
	}
	if _, ok := cursor["imported_ids"]; ok {
		t.Fatal("expected imported_ids stripped from cursor")
	}
	if _, ok := cursor["imported_paths"]; ok {
		t.Fatal("expected imported_paths stripped from cursor")
	}
}

func TestNormalizeAuditStatusFilter(t *testing.T) {
	if got := normalizeAuditStatusFilter("failed"); got != ItemStatusFailed {
		t.Fatalf("got %q", got)
	}
	if got := normalizeAuditStatusFilter("bogus"); got != "" {
		t.Fatalf("got %q", got)
	}
}

func TestIncJobStat(t *testing.T) {
	stats := map[string]any{}
	incJobStat(stats, "failed")
	incJobStat(stats, "failed")
	if stats["failed"] != float64(2) {
		t.Fatalf("failed = %v", stats["failed"])
	}
}
