import type { CommunityFiltersData } from "./CommunityFilterModal";

/**
 * Everything a change of which invalidates the community feed's accumulated
 * posts, as one string for `usePageCursor` / `usePagedItems`.
 *
 * It is built from the filter **values** rather than the filters object's
 * identity, and that is the whole point of the function. «مسح» hands back a
 * fresh `{ name: "", startDate: "", ... }` every time it is pressed. Under a
 * reference comparison each press read as a new filter: the accumulated posts
 * were cleared, the React Query key — which hashes structurally — did not
 * move, so the cached response came back as the *same* object and the
 * accumulator skipped it as already merged. The feed went blank and stayed
 * blank. Compared by value, pressing «مسح» on an unfiltered feed is correctly
 * not a change at all.
 *
 * `tag` is the tag in the URL on the "View All" route, which also decides
 * *which* query runs; the feed itself passes none.
 */
export function communityResetSignature({
  search,
  filters,
  tag,
}: {
  search: string;
  filters: CommunityFiltersData;
  tag?: string | null;
}): string {
  /* Field by field, not `JSON.stringify(filters)` — key order is whatever the
     object was built with, and the modal's values and the cleared defaults are
     not built in the same place. Two equal filter sets must produce one
     string. */
  const tags = [...(filters.tags ?? [])].sort().join(",");
  return [
    tag ?? "",
    search,
    filters.name ?? "",
    filters.startDate ?? "",
    filters.endDate ?? "",
    filters.type ?? "",
    tags,
  ].join("|");
}
