All files / src/modules/search search.service.ts

69.68% Statements 154/221
60.28% Branches 85/141
80% Functions 32/40
73.09% Lines 144/197

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830  16x             16x 16x 16x                               16x 16x   16x 16x 16x   16x             16x                                                                       16x 9x   9x     9x 9x   9x             3x       4x 4x       4x 4x 3x 3x   1x                                                                             1x       4x 4x 3x 3x   1x                   1x       1x     1x 1x 1x                             1x 1x   1x 1x 1x   1x                                                                                                             1x 1x                                                                                                     4x         4x                         1x   1x                                     1x             1x       2x   1x                     1x 1x 2x 2x     1x       2x   1x                     1x 1x                                                                                                                                                 15x 15x 15x   15x         15x         15x     15x     15x     15x       15x     15x     15x     15x     15x         15x         15x                     15x                             15x               15x       14x 14x   2x 2x   2x 2x   2x 2x   2x 2x   2x 2x   4x 4x     14x 14x       14x 14x   14x 1x                 14x                                                                                   14x 14x   14x               14x 1x   13x     14x   14x 14x       14x 14x   14x       2x                                                                                   3x 2x 2x 2x         2x         14x       2x                           1x                   1x       1x           1x     1x 1x               1x 1x 1x       1x 1x   1x                       1x                     1x         1x 1x 1x   1x 1x 1x         2x 2x             2x            
// src/modules/search/search.service.ts
import {
  Injectable,
  Logger,
  OnModuleInit,
  Inject,
  NotFoundException,
} from "@nestjs/common";
import { PrismaService } from "@app/modules/prisma/prisma.service";
import { Client as ESClient } from "@elastic/elasticsearch";
import { ELASTICSEARCH_CLIENT } from "@app/modules/search/elasticsearch.module";
import { SaveSearchDto } from "@app/modules/search/dto/save-search.dto";
import { SearchFilterInput } from "@app/modules/search/dto/search-filter.input";
import { SearchResult } from '@app/modules/search/dto/search-result.object';
// Removed unused import
 
export interface SearchServiceResponse {
  resultIds: string[];
  facets?: Record<string, any>;
  searchAfter?: (string | number)[];
}
import {
  FilterManifestResponse,
  FilterDefinition,
} from '@app/modules/search/dto/filter-manifest.dto';
import { SearchResponse } from '@elastic/elasticsearch/lib/api/types';
import NodeGeocoder from 'node-geocoder';
import * as regionsData from '@app/data/regions.json';
 
const LISTINGS_INDEX = "listings";
const AUTOCOMPLETE_INDEX = "listings-autocomplete";
const BULK_CHUNK_SIZE = 1000;
 
const BOOST_WEIGHTS: Record<string, number> = {
  STANDARD: 1.0,
  PREMIUM: 1.3,
  DIAMOND: 1.6,
};
 
// Future-proof against Prisma client type changes by using minimal local types
const fullListingInclude = {
  include: {
    address: true,
    user: { include: { agency: true } },
    photos: true,
    boosts: { where: { active: true } },
    openHouses: true,
    amenities: true,
  },
} as const;
 
type FullListing = {
  id: number;
  title: string;
  description: string;
  type: string;
  transactionType: string;
  price: number;
  currency: string;
  area: number | null;
  floor: number | null;
  rooms: number | null;
  totalFloors?: number | null;
  elevator?: boolean | null;
  balcony?: boolean | null;
  furnished?: boolean | null;
  renovated?: boolean | null;
  createdAt: Date;
  address: { id: number; city: string; country: string; street?: string | null; latitude?: number | null; longitude?: number | null };
  user: { role?: string; agencyId?: number | null; agency?: { isVerified?: boolean | null } | null };
  photos: Array<{ url: string }>;
  boosts: Array<{ tier: keyof typeof BOOST_WEIGHTS }>;
  openHouses?: Array<{ startTime: Date; endTime: Date }>;
};
 
@Injectable()
export class SearchService implements OnModuleInit {
  private readonly logger = new Logger(SearchService.name);
  private geocoder: NodeGeocoder.Geocoder;
  private regionsData: any = (regionsData as any).regions;
 
  constructor(
    @Inject(ELASTICSEARCH_CLIENT) private readonly es: ESClient,
    private readonly prisma: PrismaService,
  ) {
    this.geocoder = NodeGeocoder({
      provider: 'openstreetmap',
      formatter: null,
    });
  }
 
  async onModuleInit() {
    await this.ensureIndexesAndMappings();
  }
 
  async ensureIndexesAndMappings() {
    await this.createListingsIndex();
    await this.createAutocompleteIndex();
  }
 
  private async createListingsIndex() {
    const exists = await this.es.indices.exists({ index: LISTINGS_INDEX });
    if (exists) {
      this.logger.log(`Index ${LISTINGS_INDEX} already exists.`);
      return;
    }
    await this.es.indices.create({
      index: LISTINGS_INDEX,
      mappings: {
        properties: {
          id: { type: "keyword" },
          title: {
            type: "search_as_you_type",
            max_shingle_size: 3,
          },
          description: { type: "text", analyzer: "standard" },
          type: { type: "keyword" },
          transactionType: { type: "keyword" },
          price: { type: "float" },
          currency: { type: "keyword" },
          area: { type: "float" },
          floor: { type: "integer" },
          rooms: { type: "integer" },
          location: { type: "geo_point" },
          city: { type: "keyword" },
          country: { type: "keyword" },
          postedBy: { type: "keyword" },
          agencyId: { type: "keyword" },
          isVerified: { type: "boolean" },
          hasPhotos: { type: "boolean" },
          createdAt: { type: "date" },
          nextOpenHouseDate: { type: "date" },
          boostWeight: { type: "float" },
          // Derived fields for filtering/sorting/facets
          price_base: { type: "float" }, // price in a base currency (e.g., USD)
          price_per_sqm: { type: "float" },
          districtId: { type: "keyword" },
          floors_total: { type: "integer" },
          has_elevator: { type: "boolean" },
          has_balcony: { type: "boolean" },
          is_furnished: { type: "boolean" },
          is_renovated: { type: "boolean" },
        },
      },
    });
    this.logger.log(`Created index mapping for ${LISTINGS_INDEX}`);
  }
 
  private async createAutocompleteIndex() {
    const exists = await this.es.indices.exists({ index: AUTOCOMPLETE_INDEX });
    if (exists) {
      this.logger.log(`Index ${AUTOCOMPLETE_INDEX} already exists.`);
      return;
    }
    await this.es.indices.create({
      index: AUTOCOMPLETE_INDEX,
      mappings: {
        properties: {
          city: { type: "search_as_you_type" },
          country: { type: "search_as_you_type" },
          street: { type: "search_as_you_type" },
        },
      },
    });
    this.logger.log(`Created index mapping for ${AUTOCOMPLETE_INDEX}`);
  }
 
  async indexAllListings() {
    const listings: FullListing[] = (await this.prisma.client.listing.findMany({
      ...(fullListingInclude as any),
    })) as any;
    if (listings.length === 0) {
      this.logger.log("No listings to index.");
      return;
    }
 
    const listingBody = (await Promise.all(
      listings.map((l) => this.buildListingDocument(l)),
    )).flat();
    const locationBody = listings.flatMap((l) => this.buildLocationDocument(l));
 
    await this.bulkIndex(LISTINGS_INDEX, listingBody);
    await this.bulkIndex(AUTOCOMPLETE_INDEX, locationBody);
 
    this.logger.log(`Indexed ${listings.length} listings and locations.`);
  }
 
  private async buildListingDocument(l: FullListing) {
    const { latitude, longitude } = l.address;
    Iif (latitude == null || longitude == null) return [];
 
    let postedBy = "private";
    Iif (l.user && (l.user as any).role === 'AGENT') postedBy = "agent";
    else Iif (l.user && (l.user as any).role === 'DEVELOPER') postedBy = "developer";
 
    return [
      { index: { _index: LISTINGS_INDEX, _id: l.id.toString() } },
      {
        id: l.id.toString(),
        title: l.title,
        description: l.description,
        type: l.type,
        transactionType: l.transactionType,
        price: l.price,
        currency: l.currency,
        area: l.area,
        floor: l.floor,
        rooms: l.rooms,
        location: { lat: latitude, lon: longitude },
        city: l.address.city,
        country: l.address.country,
        postedBy: postedBy,
        agencyId: l.user.agencyId?.toString(),
        isVerified: (l as any).isVerified || l.user?.agency?.isVerified || false,
        hasPhotos: l.photos.length > 0,
        createdAt: l.createdAt,
        nextOpenHouseDate:
          (l.openHouses as Array<{ startTime: Date; endTime: Date }> | undefined)
            ?.filter((oh: { endTime: Date }) => oh.endTime > new Date())
            .sort(
              (
                a: { startTime: Date },
                b: { startTime: Date },
              ) => a.startTime.getTime() - b.startTime.getTime(),
            )[0]
            ?.startTime ?? null,
        boostWeight:
          l.boosts && l.boosts.length > 0
            ? BOOST_WEIGHTS[l.boosts[0].tier]
            : 1.0,
        // Add derived fields
        price_base: this.convertToBaseCurrency(l.price, l.currency),
        price_per_sqm:
          l.area && l.area > 0
            ? this.convertToBaseCurrency(l.price, l.currency) / l.area
            : null,
        districtId:
          l.address.latitude && l.address.longitude
            ? await this.resolveDistrictId(l.address.latitude, l.address.longitude)
            : null,
        floors_total: l.totalFloors,
        has_elevator: l.elevator ?? false,
        has_balcony: l.balcony ?? false,
        is_furnished: l.furnished ?? false,
        is_renovated: l.renovated ?? false,
      },
    ];
  }
 
  private buildLocationDocument(l: FullListing) {
    Iif (!l.address) return [];
    return [
      { index: { _index: AUTOCOMPLETE_INDEX, _id: l.address.id.toString() } },
      {
        city: l.address.city,
        country: l.address.country,
        street: l.address.street,
      },
    ];
  }
 
 
    private async resolveDistrictId(
    latitude: number,
    longitude: number,
  ): Promise<number | null> {
    Iif (!this.geocoder || !this.regionsData) return null;
 
    try {
      const res = await this.geocoder.reverse({ lat: latitude, lon: longitude });
      Iif (res && res.length > 0) {
        const geocodedDistrictName = res[0].city; // Or another field like 'administrativeLevels.level2long'
 
        Iif (!geocodedDistrictName) return null;
 
        // Find the district in our regions data
        for (const region of this.regionsData) {
          for (const district of region.districts) {
            // Check against different name variations
            Iif (
              district.name_en.toLowerCase() === geocodedDistrictName.toLowerCase() ||
              district.name_ru.toLowerCase() === geocodedDistrictName.toLowerCase() ||
              district.name_uz.toLowerCase() === geocodedDistrictName.toLowerCase()
            ) {
              return district.id;
            }
          }
        }
      }
    } catch (error) {
      this.logger.error(
        `Failed to resolve district for coords ${latitude},${longitude}`,
        error,
      );
    }
 
    return null;
  }
 
  private convertToBaseCurrency(price: number, currency: string): number {
    // Basic currency conversion, assuming USD as base
    // In a real app, use a proper currency conversion library/service
    const rates: Record<string, number> = {
      USD: 1,
      EUR: 1.1,
      UZS: 0.00008,
    };
    return price * (rates[currency] ?? 1);
  }
 
  private async bulkIndex(index: string, body: any[]) {
    Iif (body.length === 0) return;
    for (let i = 0; i < body.length; i += BULK_CHUNK_SIZE * 2) {
      const chunk = body.slice(i, i + BULK_CHUNK_SIZE * 2);
      await this.es.bulk({ refresh: true, body: chunk });
    }
  }
 
 
  async mapSearch(filter: SearchFilterInput): Promise<SearchResult[]> {
    const filterClauses = this.buildFilterClauses(filter);
 
    Iif (
      filter.northEastLat &&
      filter.northEastLng &&
      filter.southWestLat &&
      filter.southWestLng
    ) {
      filterClauses.push({
        geo_bounding_box: {
          location: {
            top_left: { lat: filter.northEastLat, lon: filter.southWestLng },
            bottom_right: {
              lat: filter.southWestLat,
              lon: filter.northEastLng,
            },
          },
        },
      });
    }
 
    const res = await this.es.search({
      index: LISTINGS_INDEX,
      from: 0,
      size: 1000, // Return more results for map view
      query: { bool: { filter: filterClauses } },
    });
 
    return this.mapResults(res);
  }
 
  async autocomplete(prefix: string) {
    if (!prefix) return [];
 
    const res = await this.es.search({
      index: AUTOCOMPLETE_INDEX,
      query: {
        multi_match: {
          query: prefix,
          type: "bool_prefix",
          fields: ["city", "country", "street"],
        },
      },
    });
 
    const suggestions = new Set<string>();
    res.hits.hits.forEach((hit: any) => {
      suggestions.add(hit._source.city);
      suggestions.add(hit._source.country);
    });
 
    return Array.from(suggestions);
  }
 
  async suggest(query: string) {
    if (!query) return [];
 
    const res = await this.es.search({
      index: LISTINGS_INDEX,
      query: {
        multi_match: {
          query,
          type: "bool_prefix",
          fields: ["title", "title._2gram", "title._3gram"],
        },
      },
    });
 
    const results = this.mapResults(res);
    return results.map((r) => r.title);
  }
 
  getFilterManifest(): FilterManifestResponse {
    const filters: FilterDefinition[] = [
      { key: 'price', label: 'Price', type: 'range' },
      { key: 'area', label: 'Area', type: 'range' },
      {
        key: 'rooms',
        label: 'Rooms',
        type: 'terms',
        options: [
          { label: '1', value: '1' },
          { label: '2', value: '2' },
          { label: '3', value: '3' },
          { label: '4', value: '4' },
          { label: '5+', value: '5' },
        ],
      },
      {
        key: 'type',
        label: 'Property Type',
        type: 'terms',
        options: [
          { label: 'Apartment', value: 'APARTMENT' },
          { label: 'House', value: 'HOUSE' },
          { label: 'Land', value: 'LAND' },
          { label: 'Commercial', value: 'COMMERCIAL' },
        ],
      },
      {
        key: 'transactionType',
        label: 'Transaction',
        type: 'terms',
        options: [
          { label: 'Sale', value: 'SALE' },
          { label: 'Rent', value: 'RENT' },
        ],
      },
      {
        key: 'postedBy',
        label: 'Posted By',
        type: 'terms',
        options: [
          { label: 'Private', value: 'private' },
          { label: 'Agent', value: 'agent' },
          { label: 'Developer', value: 'developer' },
        ],
      },
      {
        key: 'createdWithin',
        label: 'Created Within',
        type: 'terms',
        options: [
          { label: '24 hours', value: '24h' },
          { label: '3 days', value: '3d' },
          { label: '7 days', value: '7d' },
          { label: '30 days', value: '30d' },
        ],
      },
      { key: 'hasPhotos', label: 'Has Photos', type: 'boolean' },
      { key: 'isVerified', label: 'Verified', type: 'boolean' },
      { key: 'is_furnished', label: 'Furnished', type: 'boolean' },
      { key: 'is_renovated', label: 'Renovated', type: 'boolean' },
      { key: 'has_elevator', label: 'Elevator', type: 'boolean' },
      { key: 'has_balcony', label: 'Balcony', type: 'boolean' },
      { key: 'floor', label: 'Floor', type: 'range' },
      { key: 'totalFloors', label: 'Total Floors', type: 'range' },
    ];
    return { filters };
  }
 
  private buildFilterClauses(filter: SearchFilterInput): any[] {
    const filterClauses: any[] = [];
    Iif (filter.type) filterClauses.push({ term: { type: filter.type } });
    Iif (filter.transactionType)
      filterClauses.push({ term: { transactionType: filter.transactionType } });
    Iif (filter.priceMin != null || filter.priceMax != null) {
      filterClauses.push({
        range: { price: { gte: filter.priceMin, lte: filter.priceMax } },
      });
    }
    Iif (filter.areaMin != null || filter.areaMax != null) {
      filterClauses.push({
        range: { area: { gte: filter.areaMin, lte: filter.areaMax } },
      });
    }
    Iif (filter.rooms && filter.rooms.length > 0) {
      filterClauses.push({ terms: { rooms: filter.rooms } });
    }
    Iif (filter.hasPhotos !== undefined) {
      filterClauses.push({ term: { hasPhotos: filter.hasPhotos } });
    }
    Iif (filter.postedBy && filter.postedBy.length > 0) {
      filterClauses.push({ terms: { postedBy: filter.postedBy } });
    }
    Iif (filter.agencyId) {
      filterClauses.push({ term: { agencyId: filter.agencyId } });
    }
    // Boolean amenity and status filters
    Iif (filter.isVerified !== undefined) {
      filterClauses.push({ term: { isVerified: filter.isVerified } });
    }
    Iif (filter.is_furnished !== undefined) {
      filterClauses.push({ term: { is_furnished: filter.is_furnished } });
    }
    Iif (filter.is_renovated !== undefined) {
      filterClauses.push({ term: { is_renovated: filter.is_renovated } });
    }
    Iif (filter.has_elevator !== undefined) {
      filterClauses.push({ term: { has_elevator: filter.has_elevator } });
    }
    Iif (filter.has_balcony !== undefined) {
      filterClauses.push({ term: { has_balcony: filter.has_balcony } });
    }
 
    // Floor range filters
    Iif (filter.floorMin != null || filter.floorMax != null) {
      filterClauses.push({
        range: { floor: { gte: filter.floorMin, lte: filter.floorMax } },
      });
    }
    Iif (filter.totalFloorsMin != null || filter.totalFloorsMax != null) {
      filterClauses.push({
        range: {
          floors_total: {
            gte: filter.totalFloorsMin,
            lte: filter.totalFloorsMax,
          },
        },
      });
    }
 
    Iif (filter.createdWithin) {
      const now = Date.now();
      const ranges: Record<string, number> = {
        "24h": 24 * 60 * 60 * 1000,
        "3d": 3 * 24 * 60 * 60 * 1000,
        "7d": 7 * 24 * 60 * 60 * 1000,
        "30d": 30 * 24 * 60 * 60 * 1000,
      };
      const ms = ranges[filter.createdWithin];
      Iif (ms) {
        filterClauses.push({
          range: { createdAt: { gte: new Date(now - ms).toISOString() } },
        });
      }
    }
    Iif (filter.latitude && filter.longitude && filter.radius) {
      filterClauses.push({
        geo_distance: {
          distance: `${filter.radius}km`,
          location: { lat: filter.latitude, lon: filter.longitude },
        },
      });
    }
    return filterClauses;
  }
 
  private buildSort(sortBy?: string): any[] {
    const sort: any[] = [];
    switch (sortBy) {
      case 'priceAsc':
        sort.push({ price_base: 'asc' });
        break;
      case 'priceDesc':
        sort.push({ price_base: 'desc' });
        break;
      case 'areaAsc':
        sort.push({ area: 'asc' });
        break;
      case 'areaDesc':
        sort.push({ area: 'desc' });
        break;
      case 'newest':
        sort.push({ createdAt: 'desc' });
        break;
      default: // recommended
        sort.push({ _score: 'desc' });
        break;
    }
    // Add a tie-breaker for consistent sorting, which is required for search_after
    sort.push({ id: 'asc' });
    return sort;
  }
 
  async search(filter: SearchFilterInput): Promise<SearchServiceResponse> {
    const must: any[] = [];
    const filterClauses: any[] = this.buildFilterClauses(filter);
 
    if (filter.text) {
      must.push({
        multi_match: {
          query: filter.text,
          fields: ["title", "description"],
          fuzziness: "AUTO",
        },
      });
    }
 
    const esQuery = {
      function_score: {
        query: {
          bool: {
            must: must.length > 0 ? must : { match_all: {} },
            filter: filterClauses,
          },
        },
        functions: [
          {
            field_value_factor: {
              field: 'boostWeight',
              factor: 1,
              modifier: 'none',
              missing: 1,
            },
          },
          {
            gauss: {
              createdAt: {
                origin: 'now',
                scale: '30d',
                offset: '7d',
                decay: 0.5,
              },
            },
            weight: 2,
          },
          {
            filter: { term: { hasPhotos: true } },
            weight: 1.5,
          },
          {
            filter: { term: { isVerified: true } },
            weight: 2,
          },
        ],
        score_mode: 'sum',
        boost_mode: 'multiply',
      },
    };
 
    const sort = this.buildSort(filter.sortBy);
    const aggs = filter.includeFacets ? this.buildAggregations() : undefined;
 
    const searchRequest: any = {
      index: LISTINGS_INDEX,
      size: filter.size ?? 20,
      query: esQuery,
      sort,
      aggs,
    };
 
    if (filter.searchAfter && filter.searchAfter.length > 0) {
      searchRequest.search_after = filter.searchAfter;
    } else {
      searchRequest.from = filter.from ?? 0;
    }
 
    const res = await this.es.search(searchRequest);
 
    const resultIds = this.mapResultIds(res);
    const facets = filter.includeFacets
      ? this.mapAggregations(res.aggregations)
      : undefined;
 
    const lastHit = res.hits.hits[res.hits.hits.length - 1];
    const searchAfter = lastHit ? lastHit.sort : undefined;
 
    return { resultIds, facets, searchAfter };
  }
 
  private buildAggregations() {
    return {
      // Facets for keyword fields
      type: { terms: { field: 'type', size: 10 } },
      transactionType: { terms: { field: 'transactionType', size: 10 } },
      rooms: { terms: { field: 'rooms', size: 10 } },
      postedBy: { terms: { field: 'postedBy', size: 10 } },
 
      // Facets for boolean fields
      hasPhotos: { terms: { field: 'hasPhotos' } },
      isVerified: { terms: { field: 'isVerified' } },
      is_furnished: { terms: { field: 'is_furnished' } },
      is_renovated: { terms: { field: 'is_renovated' } },
      has_elevator: { terms: { field: 'has_elevator' } },
      has_balcony: { terms: { field: 'has_balcony' } },
 
      // Facets for range fields
      price: {
        range: {
          field: 'price_base',
          ranges: [
            { key: '<50k', to: 50000 },
            { key: '50k-100k', from: 50000, to: 100000 },
            { key: '100k-200k', from: 100000, to: 200000 },
            { key: '>200k', from: 200000 },
          ],
        },
      },
      area: {
        range: {
          field: 'area',
          ranges: [
            { key: '<50', to: 50 },
            { key: '50-100', from: 50, to: 100 },
            { key: '100-150', from: 100, to: 150 },
            { key: '>150', from: 150 },
          ],
        },
      },
    };
  }
 
  private mapAggregations(aggregations: any): Record<string, any> | undefined {
    if (!aggregations) return undefined;
    const facets: Record<string, any> = {};
    for (const key in aggregations) {
      facets[key] = aggregations[key].buckets.map((b: any) => ({
        key: b.key.toString(),
        count: b.doc_count,
      }));
    }
    return facets;
  }
 
 
  private mapResultIds(res: SearchResponse): string[] {
    return res.hits.hits.map((hit) => hit._id).filter((id): id is string => !!id);
  }
 
  private mapResults(res: SearchResponse): SearchResult[] {
    return res.hits.hits.map((hit: any) => ({
      ...hit._source,
      id: hit._source.id,
      title: hit._source.title,
      score: hit._score,
      price: hit._source.price,
      currency: hit._source.currency,
      location: hit._source.location,
      sort: hit.sort,
    }));
  }
 
  async saveSearch(user: { id: number }, saveSearchDto: SaveSearchDto) {
    // Normalize raw filters into SearchFilters row and link via filtersId
    const created = await this.prisma.client.savedSearch.create({
      data: {
        name: saveSearchDto.name,
        userId: user.id,
        filters: {
          create: (saveSearchDto.filters as any) ?? {},
        } as any,
      },
      include: { filters: true },
    } as any);
    return created;
  }
 
  async getSavedSearches(user: { id: number }) {
    return this.prisma.client.savedSearch.findMany({
      where: { userId: user.id },
    });
  }
 
  async deleteSavedSearch(user: { id: number }, searchId: number) {
    const search = await this.prisma.client.savedSearch.findUnique({
      where: { id: searchId },
    });
    if (!search || search.userId !== user.id) {
      throw new NotFoundException(
        `Saved search with ID ${searchId} not found.`,
      );
    }
    return this.prisma.client.savedSearch.delete({ where: { id: searchId } });
  }
 
  async updateSavedSearch(user: { id: number }, id: number, body: { name?: string; cadence?: string; channel?: string }) {
    const search = await this.prisma.client.savedSearch.findUnique({ where: { id } });
    Iif (!search || search.userId !== user.id) throw new NotFoundException('Saved search not found');
    return this.prisma.client.savedSearch.update({ where: { id }, data: { name: body.name, cadence: body.cadence, channel: body.channel } as any });
  }
 
  async toggleSavedSearch(user: { id: number }, id: number) {
    const search = await this.prisma.client.savedSearch.findUnique({ where: { id } });
    Iif (!search || search.userId !== user.id) throw new NotFoundException('Saved search not found');
    // @ts-ignore enabled exists
    return this.prisma.client.savedSearch.update({ where: { id }, data: { enabled: !(search as any).enabled } });
  }
 
  async testSavedSearch(user: { id: number }, id: number) {
    const search = await this.prisma.client.savedSearch.findUnique({ where: { id } });
    Iif (!search || search.userId !== user.id) throw new NotFoundException('Saved search not found');
    // TODO: enqueue a test notification to NotificationService
    return { sent: true };
  }
 
  // Index single listing by ID (called by BullMQ worker)
  async indexListing(listingId: number) {
    const listing = await this.prisma.client.listing.findUnique({
      where: { id: listingId },
      include: {
        address: true,
        user: { include: { agency: true } },
        photos: true,
        boosts: { where: { active: true } },
        openHouses: true,
      },
    } as any);
 
    Iif (!listing) {
      this.logger.warn(`Listing ${listingId} not found, skip index.`);
      return;
    }
 
    const listingDoc = await this.buildListingDocument(listing as any);
    const locationDoc = this.buildLocationDocument(listing as any);
    const body = [...listingDoc, ...locationDoc];
 
    Iif (body.length === 0) return;
    await this.es.bulk({ refresh: true, body });
    this.logger.log(`Indexed listing ${listingId}`);
  }
 
  // Public helper for OpenHouseService to patch nextOpenHouseDate without full re-index
  async patchNextOpenHouse(listingId: number, date: Date | null) {
    try {
      await this.es.update({
        index: LISTINGS_INDEX,
        id: listingId.toString(),
        doc: { nextOpenHouseDate: date },
        doc_as_upsert: true,
      });
    } catch (err) {
      this.logger.debug(
        `ES patch failed for listing ${listingId}: ${(err as Error).message}`,
      );
    }
  }
}