package mail import ( "context" "encoding/json" "errors" "os" "testing" "time" "github.com/carlosframework/platform/internal/release" ) // The sweep is what finally removes email.json, a release after the // migration stopped writing it. It is off by default and it never deletes a // legacy record for an app that has not been migrated, because that record // is still the only copy of that app's email. func TestSweepLegacyRecordsOnlyRemovesMigratedApps(t *testing.T) { ctx := context.Background() s := release.NewDirStore(t.TempDir()) now := time.Date(2026, 9, 15, 12, 0, 0, 0, time.UTC) seed := func(app string, migrated bool) { body, _ := json.Marshal(&Record{Schema: Schema, App: app, Declared: &Declared{EnvPrefix: "P", From: "noreply@x.com", At: now, By: "o@example.test"}}) if _, err := s.Put(ctx, LegacyKey("bag", app), body, ""); err != nil { t.Fatal(err) } if migrated { if _, err := PutSender(ctx, s, "bag", app, &Sender{ID: SenderAppID, Scope: ScopeApp, Source: SourceDomain}, ""); err != nil { t.Fatal(err) } } } seed("migrated", true) seed("untouched", false) // Off by default: the flag is the whole guard, and a console that has // not been told to sweep sweeps nothing. if n, err := SweepLegacyRecords(ctx, s, false); n != 0 || err != nil { t.Fatalf("the sweep ran while disabled: %d %v", n, err) } if _, _, err := s.Get(ctx, LegacyKey("bag", "migrated")); err != nil { t.Fatalf("the disabled sweep deleted something: %v", err) } n, err := SweepLegacyRecords(ctx, s, true) if err != nil { t.Fatal(err) } if n != 1 { t.Fatalf("deleted %d, want 1", n) } if _, _, err := s.Get(ctx, LegacyKey("bag", "migrated")); !errors.Is(err, os.ErrNotExist) { t.Fatalf("the migrated app's email.json survived: %v", err) } if _, _, err := s.Get(ctx, LegacyKey("bag", "untouched")); err != nil { t.Fatalf("an unmigrated app's only record was deleted: %v", err) } // Running it twice is a no-op, which is what makes it safe at every start. if n, err := SweepLegacyRecords(ctx, s, true); n != 0 || err != nil { t.Fatalf("a second sweep = %d %v, want 0 and no error", n, err) } }