/**
 * Minimal parser for Typesense-style `filterBy` strings produced
 * by the search query handlers.
 *
 * Expected format examples:
 *   "status:=ACTIVE && propertyType:=HOUSE && priceVND:[2000..5000]"
 *   "status:=ACTIVE && priceVND:>=1000 && bedrooms:>=3"
 */

export interface ParsedFilters {
  propertyType?: string;
  transactionType?: string;
  priceMin?: number;
  priceMax?: number;
  areaMin?: number;
  areaMax?: number;
  bedrooms?: number;
  district?: string;
  city?: string;
}

export function parseFilterBy(filterStr: string): ParsedFilters {
  const result: ParsedFilters = {};
  if (!filterStr) return result;

  const clauses = filterStr.split('&&').map((c) => c.trim());
  for (const clause of clauses) {
    // Range: field:[min..max]
    const rangeMatch = clause.match(/^(\w+):\[(\d+)\.\.(\d+)\]$/);
    if (rangeMatch) {
      const field = rangeMatch[1]!;
      const min = Number(rangeMatch[2]);
      const max = Number(rangeMatch[3]);
      if (field === 'priceVND') {
        result.priceMin = min;
        result.priceMax = max;
      } else if (field === 'areaM2') {
        result.areaMin = min;
        result.areaMax = max;
      }
      continue;
    }

    // Equality: field:=value
    const eqMatch = clause.match(/^(\w+):=(.+)$/);
    if (eqMatch) {
      const field = eqMatch[1]!;
      const val = eqMatch[2]!;
      if (field === 'propertyType') result.propertyType = val;
      else if (field === 'transactionType') result.transactionType = val;
      else if (field === 'district') result.district = val;
      else if (field === 'city') result.city = val;
      else if (field === 'status') { /* handled separately */ }
      continue;
    }

    // Gte: field:>=value
    const gteMatch = clause.match(/^(\w+):>=(\d+(?:\.\d+)?)$/);
    if (gteMatch) {
      const field = gteMatch[1]!;
      const val = Number(gteMatch[2]);
      if (field === 'priceVND') result.priceMin = val;
      else if (field === 'areaM2') result.areaMin = val;
      else if (field === 'bedrooms') result.bedrooms = val;
      continue;
    }

    // Lte: field:<=value
    const lteMatch = clause.match(/^(\w+):<=(\d+(?:\.\d+)?)$/);
    if (lteMatch) {
      const field = lteMatch[1]!;
      const val = Number(lteMatch[2]);
      if (field === 'priceVND') result.priceMax = val;
      else if (field === 'areaM2') result.areaMax = val;
      continue;
    }

    // Geo filter: location:(lat, lng, radius km) -- skip, handled via params
  }

  return result;
}
