// src/lib/deals/facet-key.ts
import type { DealType } from '@/lib/deal-types';

/** Inputs that select a facet view. Empty/absent fields mean "no selection". */
export interface FacetKeyInput {
  catSlug?: string;
  type?: '' | DealType;
  tagSlugs?: string[];
  priceMin?: number;
  priceMax?: number;
  q?: string;
  cityCode?: string;
  lat?: number;
  lng?: number;
  km?: number;
  locale?: string;
  minDiscount?: number;
  preset?: string;
}

/** The normalized object embedded in the query key. */
export interface FacetKeyParams {
  catSlug: string | null;
  type: DealType | null;
  tagSlugs: string[];
  priceMin: number | null;
  priceMax: number | null;
  q: string | null;
  cityCode: string | null;
  lat: number | null;
  lng: number | null;
  km: number | null;
  locale?: string;
  minDiscount?: number;
  preset?: string;
}

/**
 * Canonical TanStack query key for /deals facet counts.
 * MUST be the single source of truth for both SSR seed and client useQuery —
 * any divergence re-introduces the sidebar blink.
 */
export function buildFacetKey(input: FacetKeyInput): readonly ['deals-facets', FacetKeyParams] {
  const params: FacetKeyParams = {
    catSlug: input.catSlug ?? null,
    type: input.type ? input.type : null,
    tagSlugs: [...(input.tagSlugs ?? [])].sort(),
    priceMin: input.priceMin ?? null,
    priceMax: input.priceMax ?? null,
    q: input.q && input.q.trim() ? input.q.trim() : null,
    cityCode: input.cityCode ? input.cityCode : null,
    lat: input.lat ?? null,
    lng: input.lng ?? null,
    km: input.km ?? null,
  };
  if (input.locale !== undefined) params.locale = input.locale;
  if (input.minDiscount !== undefined) params.minDiscount = input.minDiscount;
  if (input.preset !== undefined) params.preset = input.preset;
  return ['deals-facets', params] as const;
}
