/**
 * canonicalFilterHash — shared client+server utility.
 *
 * Deterministic SHA-256 hash of a normalized FeedFilter → 16-char hex.
 * Key-order independent, tag-order normalized, locale-independent.
 *
 * Uses Web Crypto API (available in Cloudflare Workers, modern browsers, Node ≥20).
 */

import { bytesToHex } from '@/lib/encoding';
import type { FeedFilter } from '@/server/schemas/feed.js';

/**
 * Returns the first 16 hex chars of SHA-256(JSON(normalized filter)).
 * Stable across server (CF Workers) and client (browser/jsdom).
 */
export async function canonicalFilterHash(filter: FeedFilter): Promise<string> {
  const normalized = {
    cityCode: filter.cityCode ?? null,
    radius: filter.radius
      ? { lat: filter.radius.lat, lng: filter.radius.lng, km: filter.radius.km }
      : null,
    dealType: filter.dealType ?? null,
    categoryId: filter.categoryId ?? null,
    tagIds: filter.tagIds ? [...filter.tagIds].sort() : null,
    minPrice: filter.minPrice ?? null,
    maxPrice: filter.maxPrice ?? null,
    hours: filter.hours,
    cursor: filter.cursor ?? null,
    limit: filter.limit,
    page: filter.page ?? null,
    preset: filter.preset ?? null,
  };

  const encoded = new TextEncoder().encode(JSON.stringify(normalized));
  const hashBuf = await crypto.subtle.digest('SHA-256', encoded);
  return bytesToHex(hashBuf).slice(0, 16);
}
