All files / routes/marketplace search.routes.ts

96.15% Statements 225/234
92.7% Branches 216/233
93.75% Functions 15/16
97.11% Lines 202/208

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                                                          61x 61x 61x 61x 61x           171x                   61x 61x 61x 61x   61x   61x 60x   60x 60x 2x                     58x     58x   58x 7x 7x 3x 1x               2x       57x       60x     60x 60x 60x     60x     60x 60x     60x 60x 60x 57x     57x   57x   57x         57x 57x 57x 57x 57x         57x                         57x   57x   57x 57x   57x 34x 34x           33x 33x           33x           33x           33x 34x     34x 7x 7x   33x           33x                     55x                           2x                   57x         57x 57x 4x   57x 1x     57x                             34x     32x 32x 32x 32x   32x 35x   12x 12x   5x 5x   9x 9x   9x 9x         32x                   31x 31x 4x     31x 31x 8x       31x 31x 8x     31x                   31x 31x 6x     31x 31x 8x 8x 6x     31x 6x     6x       31x 34x   11x 11x 10x                         5x 5x 4x 4x                                           9x 9x 8x 8x     9x                                                     9x 9x 5x                                                 31x         31x         31x             31x 31x   31x 31x   31x 31x   31x 31x       10x 2x 2x 1x 1x 1x 1x         31x                                   34x 34x 6x 5x 6x 4x 4x         31x   31x         34x       34x 2x 2x 1x         1x 1x         31x 8x     31x 34x 34x 3x       31x     5x 5x       31x                                                   31x 31x           31x 31x 11x 11x 10x                                 31x 31x 5x 5x 4x 4x                                     31x 31x 9x 9x 8x 8x     9x 9x                                   31x 31x 9x 9x 5x 9x 9x                               1x         31x                     34x        
// Search API endpoint for marketplace full-text search
import { getRoomCategorySlug } from "@interioring/utils/constants/room-categories";
import { Hono } from "hono";
import { SearchService } from "../../lib/search/search-service";
import type { EntityType, SearchResult } from "../../lib/search/types";
import { handleError, success } from "../../lib/response";
import type { ContextVariables } from "../../middleware";
import type { Dal } from "../../dal";
import {
	type BusinessType,
	businessTypes,
	blogCategories as blogCategoriesTable,
	type City,
	cities,
	type Zone,
	zones,
	type Locality,
	localities,
	projects,
} from "../../db/schema";
import { and, desc, eq, inArray, isNotNull } from "drizzle-orm";
import type { getDb } from "../../db";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
 
const VALID_TYPES = new Set<EntityType>(["pro", "project", "room", "blog"]);
const MAX_LIMIT = 50;
const DEFAULT_LIMIT = 10;
const MIN_QUERY_LENGTH = 2;
const MAX_FACET_IDS = 20;
 
// Parse a comma-separated id list, trimming, dropping empties, and enforcing
// the same per-filter cap the pros DAL uses so a malicious caller can't blow
// up the in-memory facet check.
function parseIdList(raw: string | undefined): string[] | undefined {
	Eif (!raw) return undefined;
	const ids = raw
		.split(",")
		.map((id) => id.trim())
		.filter(Boolean)
		.slice(0, MAX_FACET_IDS);
	return ids.length > 0 ? ids : undefined;
}
 
// Module-scope warm cache for search service (persists across requests in same isolate)
let cachedService: SearchService | null = null;
let cachedVersion: string | null = null;
let lastVersionCheck = 0;
const VERSION_CHECK_INTERVAL = 60_000; // 60 seconds
 
const search = new Hono<Env>();
 
search.get("/", async (c) => {
	try {
		// 1. Validate query params
		const q = c.req.query("q")?.trim();
		if (!q || q.length < MIN_QUERY_LENGTH) {
			return c.json(
				{
					success: false,
					error: `Query parameter "q" is required and must be at least ${MIN_QUERY_LENGTH} characters`,
				},
				400,
			);
		}
 
		// Sanitize: strip control characters, limit length
		// biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally stripping control characters from user input
		const sanitizedQuery = q.replace(/[\x00-\x1f]/g, "").substring(0, 200);
 
		// Parse types (comma-separated, validate each)
		const typesParam = c.req.query("types");
		let types: EntityType[] | undefined;
		if (typesParam) {
			const parsed = typesParam.split(",").map((t) => t.trim()) as EntityType[];
			const invalid = parsed.filter((t) => !VALID_TYPES.has(t));
			if (invalid.length > 0) {
				return c.json(
					{
						success: false,
						error: `Invalid type(s): ${invalid.join(", ")}. Valid types: pro, project, room, blog`,
					},
					400,
				);
			}
			types = parsed;
		}
 
		// Parse limit and page
		const limit = Math.min(
			Math.max(1, Number(c.req.query("limit")) || DEFAULT_LIMIT),
			MAX_LIMIT,
		);
		const page = Math.max(1, Number(c.req.query("page")) || 1);
 
		// Parse facet filters (applied post-search against indexed facet fields)
		const cityIds = parseIdList(c.req.query("cityIds"));
		const localityId = c.req.query("localityId")?.trim() || undefined;
		const serviceCategoryIds = parseIdList(
			c.req.query("serviceCategoryIds"),
		);
		const materialTagIds = parseIdList(c.req.query("materialTagIds"));
 
		// Parse diversity mode: "strict" = max-1-per-pro (for autocomplete dropdowns)
		const diversityParam = c.req.query("diversity");
		const diversity = diversityParam === "strict" ? "strict" as const : "default" as const;
 
		// 2. Load or reuse cached SearchService (throttle KV version checks to once per 60s)
		const now = Date.now();
		let currentVersion = cachedVersion;
		if (!cachedService || now - lastVersionCheck > VERSION_CHECK_INTERVAL) {
			currentVersion = c.env.KV_CACHE
				? await c.env.KV_CACHE.get("search-index-version")
				: null;
			lastVersionCheck = now;
		}
		Eif (!cachedService || cachedVersion !== currentVersion) {
			// Build dictionary from taxonomy tables for typo correction
			const dictionary = await buildDictionary(c.get("dal"));
			// Read env-tunable weights (SEARCH_RELEVANCE_WEIGHT / SEARCH_QUALITY_WEIGHT).
			// Defaults: 0.7 / 0.3 (70% text relevance, 30% quality score).
			// Cast through unknown because CloudflareBindings is a typed interface and these
			// vars may not be declared until wrangler.jsonc is updated (Lane B).
			const env = c.env as unknown as Record<string, unknown>;
			const relevanceWeight = Number(env.SEARCH_RELEVANCE_WEIGHT) || 0.7;
			const qualityWeight = Number(env.SEARCH_QUALITY_WEIGHT) || 0.3;
			cachedService = await SearchService.fromR2(c.env.R2, dictionary, relevanceWeight, qualityWeight);
			cachedVersion = currentVersion;
		}
 
		// 3. Run search (facet filters applied inside SearchService against
		// indexed facet fields; result counts reflect post-filter totals).
		const searchResponse = cachedService.search({
			q: sanitizedQuery,
			types,
			limit,
			page,
			cityIds,
			localityId,
			serviceCategoryIds,
			materialTagIds,
			diversity,
		});
 
		// 4. Enrich results with entity data (only for full SSR page, not autocomplete dropdown)
		const enrich = c.req.query("enrich");
 
		let enrichedResults = searchResponse.results;
		let richData: Record<string, unknown> | undefined;
		let counts = searchResponse.counts;
		let total = searchResponse.total;
 
		if (enrich === "full") {
			const dal = c.get("dal");
			const enrichment = await enrichSearchResults(
				searchResponse.results,
				dal,
				c.get("db"),
				{ includeRichData: true },
			);
			enrichedResults = enrichment.results;
			richData = enrichment.richData;
 
			// Drop results the DB no longer resolves (stale R2 index pointing at
			// deleted blogs/pros/projects/rooms). Without this filter the SSR
			// renderer would silently emit `null` cards while the type-tab badge
			// kept showing the index count — bug #569.
			const richKeyByType = {
				pro: "pros",
				project: "projects",
				room: "rooms",
				blog: "blogs",
			} as const;
			const dropped: Record<EntityType, number> = {
				pro: 0,
				project: 0,
				room: 0,
				blog: 0,
			};
			enrichedResults = enrichedResults.filter((r) => {
				const bucket = richData?.[richKeyByType[r.type]] as
					| Record<string, unknown>
					| undefined;
				if (bucket && bucket[r.id] !== undefined) return true;
				dropped[r.type]++;
				return false;
			});
			counts = {
				pro: Math.max(0, counts.pro - dropped.pro),
				project: Math.max(0, counts.project - dropped.project),
				room: Math.max(0, counts.room - dropped.room),
				blog: Math.max(0, counts.blog - dropped.blog),
			};
			total = Math.max(
				0,
				total -
					dropped.pro -
					dropped.project -
					dropped.room -
					dropped.blog,
			);
		}
 
		// 5. Return response
		return success(c, {
			results: enrichedResults,
			query: searchResponse.query,
			corrected: searchResponse.corrected,
			total,
			counts,
			...(richData ? { richData } : {}),
			meta: {
				page,
				limit,
				totalPages: Math.ceil(total / limit),
			},
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Search index rebuild is available at /api/admin/search/rebuild (requires platform admin auth)
 
/**
 * Build a dictionary of terms from taxonomy tables for typo correction.
 */
async function buildDictionary(dal: Dal): Promise<string[]> {
	const [roomTypes, blogCategories] = await Promise.all([
		dal.roomTypes.findAll(),
		dal.blogCategories.findAll(),
	]);
 
	const terms: string[] = [];
	for (const rt of roomTypes) {
		terms.push(rt.displayName);
	}
	for (const bc of blogCategories) {
		terms.push(bc.name);
	}
 
	return terms;
}
 
/**
 * Unified enrichment: batch-fetches entities ONCE, builds flat SearchResult[]
 * and optionally builds richData for SSR card rendering.
 * This eliminates the double DB queries that occurred when enrichResults() and
 * buildRichData() were separate functions.
 */
async function enrichSearchResults(
	results: SearchResult[],
	dal: Dal,
	db: ReturnType<typeof getDb>,
	options: { includeRichData: boolean },
): Promise<{ results: SearchResult[]; richData?: Record<string, unknown> }> {
	if (results.length === 0) return { results: [] };
 
	// Group IDs by entity type
	const proIds: string[] = [];
	const projectIds: string[] = [];
	const roomIds: number[] = [];
	const blogIds: string[] = [];
 
	for (const r of results) {
		switch (r.type) {
			case "pro":
				proIds.push(r.id);
				break;
			case "project":
				projectIds.push(r.id);
				break;
			case "room":
				roomIds.push(Number(r.id));
				break;
			case "blog":
				blogIds.push(r.id);
				break;
		}
	}
 
	// Batch fetch all entities in parallel (SINGLE fetch, shared by both enrichment + richData)
	const [prosMap, projectsMap, roomsMap, blogsMap] = await Promise.all([
		proIds.length > 0 ? dal.pros.findByIds(proIds) : new Map(),
		projectIds.length > 0
			? dal.projects.findByIds(projectIds)
			: new Map(),
		roomIds.length > 0 ? dal.rooms.findByIds(roomIds) : new Map(),
		blogIds.length > 0 ? dal.blogs.findByIds(blogIds) : new Map(),
	]);
 
	// Collect proIds needed for project/room lookups
	const neededProIds = new Set<string>();
	for (const project of projectsMap.values()) {
		neededProIds.add(project.proId);
	}
	// Collect projectIds needed for room lookups
	const neededProjectIds = new Set<string>();
	for (const room of roomsMap.values()) {
		neededProjectIds.add(room.projectId);
	}
 
	// Fetch parent entities for subtitle enrichment (only if not already loaded)
	const missingProIds = [...neededProIds].filter((id) => !prosMap.has(id));
	const missingProjectIds = [...neededProjectIds].filter(
		(id) => !projectsMap.has(id),
	);
 
	const [extraPros, extraProjects] = await Promise.all([
		missingProIds.length > 0
			? dal.pros.findByIds(missingProIds)
			: new Map(),
		missingProjectIds.length > 0
			? dal.projects.findByIds(missingProjectIds)
			: new Map(),
	]);
 
	// Merge extra lookups
	for (const [id, pro] of extraPros) prosMap.set(id, pro);
	for (const [id, project] of extraProjects)
		projectsMap.set(id, project);
 
	// Also get parent pros for rooms via their projects (needed for both enrichment + richData)
	const roomParentProIds = new Set<string>();
	for (const room of roomsMap.values()) {
		const project = projectsMap.get(room.projectId);
		if (project && !prosMap.has(project.proId)) {
			roomParentProIds.add(project.proId);
		}
	}
	if (roomParentProIds.size > 0) {
		const moreExtraPros = await dal.pros.findByIds([
			...roomParentProIds,
		]);
		for (const [id, pro] of moreExtraPros) prosMap.set(id, pro);
	}
 
	// --- Build flat enriched results (always) ---
	const enrichedResults = results.map((r) => {
		switch (r.type) {
			case "pro": {
				const pro = prosMap.get(r.id);
				if (!pro) return r;
				return {
					...r,
					title: pro.businessName,
					url: `/pros/${pro.slug}`,
					logo: pro.logoUrl ?? pro.profileImage ?? null,
					images: pro.coverImage ? [pro.coverImage] : [],
					meta: {
						slug: pro.slug,
						businessTypeId: pro.businessTypeId,
					},
				};
			}
			case "project": {
				const project = projectsMap.get(r.id);
				if (!project) return r;
				const parentPro = prosMap.get(project.proId);
				return {
					...r,
					title: project.title,
					subtitle: parentPro
						? `by ${parentPro.businessName}`
						: "",
					url: `/projects/${project.slug}`,
					logo:
						parentPro?.logoUrl ??
						parentPro?.profileImage ??
						null,
					images: project.coverImage
						? [project.coverImage]
						: [],
					meta: {
						slug: project.slug,
						proName: parentPro?.businessName ?? null,
						propertyType: project.propertyType ?? null,
					},
				};
			}
			case "room": {
				const room = roomsMap.get(Number(r.id));
				if (!room) return r;
				const parentProject = projectsMap.get(room.projectId);
				const parentPro = parentProject
					? prosMap.get(parentProject.proId)
					: undefined;
				return {
					...r,
					title: room.name ?? room.roomType,
					subtitle: [
						parentPro
							? `by ${parentPro.businessName}`
							: "",
						parentProject ? parentProject.title : "",
					]
						.filter(Boolean)
						.join(" \u00b7 "),
					url: `/rooms/${getRoomCategorySlug(room.roomType ?? "")}/${room.slug}`,
					logo:
						parentPro?.logoUrl ??
						parentPro?.profileImage ??
						null,
					images: [],
					meta: {
						slug: room.slug,
						proName: parentPro?.businessName ?? null,
						projectTitle: parentProject?.title ?? null,
						roomType: room.roomType,
						styleTags: room.styleTags ?? [],
					},
				};
			}
			case "blog": {
				const blog = blogsMap.get(r.id);
				if (!blog) return r;
				return {
					...r,
					title: blog.title,
					subtitle: blog.readTimeMinutes
						? `${blog.readTimeMinutes} min read`
						: "",
					url: `/blog/${blog.slug}`,
					logo: null,
					images: blog.featuredImageUrl
						? [blog.featuredImageUrl]
						: [],
					meta: {
						slug: blog.slug,
						categoryId: blog.categoryId,
						readTimeMinutes: blog.readTimeMinutes,
						publishedAt: blog.publishedAt,
					},
				};
			}
			default:
				return r;
		}
	});
 
	// --- Build rich data (only when requested) ---
	Iif (!options.includeRichData) {
		return { results: enrichedResults };
	}
 
	// Fetch taxonomy data for enrichment (business types, cities)
	const allProIds = [
		...new Set([...proIds, ...neededProIds, ...roomParentProIds]),
	];
 
	const [taxonomyBt, taxonomyCities, taxonomyZones, taxonomyLocalities] =
		await Promise.all([
			db.select().from(businessTypes),
			db.select().from(cities),
			db.select().from(zones),
			db.select().from(localities),
		]);
 
	const btMap = new Map<string, BusinessType>();
	for (const bt of taxonomyBt) btMap.set(bt.id, bt);
 
	const cityMap = new Map<string, City>();
	for (const ct of taxonomyCities) cityMap.set(ct.id, ct);
 
	const zoneMap = new Map<string, Zone>();
	for (const z of taxonomyZones) zoneMap.set(z.id, z);
 
	const localityMap = new Map<string, Locality>();
	for (const l of taxonomyLocalities) localityMap.set(l.id, l);
 
	// Helper to resolve city name from pro's serviceAreaIds
	function resolveCity(serviceAreaIds: string[] | null): string | null {
		if (!serviceAreaIds || serviceAreaIds.length === 0) return null;
		const locality = localityMap.get(serviceAreaIds[0]);
		if (!locality) return null;
		const zone = zoneMap.get(locality.zoneId);
		Iif (!zone) return null;
		const city = cityMap.get(zone.cityId);
		return city?.name ?? null;
	}
 
	// Fetch portfolio covers for pro cards (batch query)
	const coverPhotos =
		allProIds.length > 0
			? await db
					.select({
						proId: projects.proId,
						coverImage: projects.coverImage,
					})
					.from(projects)
					.where(
						and(
							inArray(projects.proId, allProIds),
							eq(projects.status, "published"),
							isNotNull(projects.coverImage),
						),
					)
					.orderBy(desc(projects.dateCreated))
					.limit(allProIds.length * 4)
			: [];
 
	const coversByProId = new Map<string, string[]>();
	for (const row of coverPhotos) {
		if (!row.coverImage) continue;
		const existing = coversByProId.get(row.proId) ?? [];
		if (existing.length < 4) {
			existing.push(row.coverImage);
			coversByProId.set(row.proId, existing);
		}
	}
 
	// Fetch room media for room cards (cover image + count)
	const allRoomIds = [...roomsMap.keys()];
	const roomMedia =
		allRoomIds.length > 0
			? await dal.media.findByRoomIds(allRoomIds)
			: [];
 
	// Group media by roomId: { coverImage, mediaCount }
	const roomMediaMap = new Map<
		number,
		{ coverImage: string | null; mediaCount: number }
	>();
	for (const m of roomMedia) {
		const existing = roomMediaMap.get(m.roomId);
		if (!existing) {
			roomMediaMap.set(m.roomId, {
				coverImage: m.isCover ? m.storageKey : m.storageKey,
				mediaCount: 1,
			});
		} else {
			existing.mediaCount++;
			Eif (m.isCover) existing.coverImage = m.storageKey;
		}
	}
 
	// Fetch room type display names
	const roomTypeCodes = [
		...new Set([...roomsMap.values()].map((r) => r.roomType)),
	];
	const roomTypeEntries =
		roomTypeCodes.length > 0 ? await dal.roomTypes.findAll() : [];
	const roomTypeMap = new Map<string, string>();
	for (const rt of roomTypeEntries) {
		roomTypeMap.set(rt.code, rt.displayName);
	}
 
	// Fetch blog categories (batch query instead of N+1) and tags
	const allCategoryIds = [
		...new Set(
			[...blogsMap.values()]
				.map((b) => b.categoryId)
				.filter((id): id is string => id !== null),
		),
	];
 
	const [blogTagMap, blogCategoryEntries, blogProsMap] = await Promise.all(
		[
			blogIds.length > 0
				? dal.blogTags.findByBlogIds(blogIds)
				: new Map(),
			allCategoryIds.length > 0
				? db
						.select()
						.from(blogCategoriesTable)
						.where(
							inArray(
								blogCategoriesTable.id,
								allCategoryIds,
							),
						)
				: [],
			blogIds.length > 0
				? dal.blogPros.findProsByBlogIds(
						blogIds,
						"approved",
						"published",
					)
				: new Map(),
		],
	);
 
	const blogCatMap = new Map<string, { name: string }>();
	for (const cat of blogCategoryEntries) {
		if (cat) blogCatMap.set(cat.id, { name: cat.name });
	}
 
	// === Build rich data objects ===
 
	const richPros: Record<string, unknown> = {};
	for (const id of proIds) {
		const pro = prosMap.get(id);
		if (!pro) continue;
		richPros[id] = {
			id: pro.id,
			slug: pro.slug,
			businessName: pro.businessName,
			businessType: pro.businessTypeId
				? (btMap.get(pro.businessTypeId)?.name ?? null)
				: null,
			profileImage: pro.profileImage ?? null,
			logoUrl: pro.logoUrl ?? null,
			city: resolveCity(pro.serviceAreaIds),
			budgetRange: null,
			isEarlyAdopter: pro.isEarlyAdopter,
			featuredProjectImage: null,
			portfolioCovers: coversByProId.get(pro.id) ?? [],
		};
	}
 
	const richProjects: Record<string, unknown> = {};
	for (const id of projectIds) {
		const project = projectsMap.get(id);
		if (!project) continue;
		const parentPro = prosMap.get(project.proId);
		richProjects[id] = {
			id: project.id,
			slug: project.slug,
			title: project.title,
			coverImage: project.coverImage ?? null,
			propertyType: project.propertyType ?? null,
			budgetRange: project.budgetRange ?? null,
			pro: parentPro
				? {
						id: parentPro.id,
						businessName: parentPro.businessName,
						slug: parentPro.slug,
						profileImage: parentPro.profileImage ?? null,
						logoUrl: parentPro.logoUrl ?? null,
					}
				: null,
		};
	}
 
	const richRooms: Record<string, unknown> = {};
	for (const id of roomIds) {
		const room = roomsMap.get(id);
		if (!room) continue;
		const parentProject = projectsMap.get(room.projectId);
		const parentPro = parentProject
			? prosMap.get(parentProject.proId)
			: undefined;
		const mediaInfo = roomMediaMap.get(id);
		richRooms[String(id)] = {
			slug: room.slug,
			roomType: room.roomType,
			roomTypeName:
				roomTypeMap.get(room.roomType) ?? room.roomType,
			name: room.name ?? null,
			coverImage: mediaInfo?.coverImage ?? null,
			mediaCount: mediaInfo?.mediaCount ?? 0,
			projectTitle: parentProject?.title ?? null,
			proBusinessName: parentPro?.businessName ?? null,
			proAvatar:
				parentPro?.logoUrl ??
				parentPro?.profileImage ??
				null,
			categorySlug: room.roomType,
		};
	}
 
	const richBlogs: Record<string, unknown> = {};
	for (const id of blogIds) {
		const blog = blogsMap.get(id);
		if (!blog) continue;
		const bPros = blogProsMap.get(id) || [];
		const primaryPro = bPros[0] ?? null;
		richBlogs[id] = {
			id: blog.id,
			slug: blog.slug,
			title: blog.title,
			metaDescription: blog.metaDescription ?? null,
			featuredImageUrl: blog.featuredImageUrl ?? null,
			featuredImageAlt: blog.featuredImageAlt ?? null,
			readTimeMinutes: blog.readTimeMinutes ?? null,
			publishedAt: blog.publishedAt ?? null,
			category: blog.categoryId
				? (blogCatMap.get(blog.categoryId) ?? null)
				: null,
			pro: primaryPro
				? { businessName: primaryPro.businessName }
				: null,
			tags: (blogTagMap.get(id) || []).map(
				(t: { name: string }) => ({ name: t.name }),
			),
		};
	}
 
	const richData: Record<string, unknown> = {
		...(Object.keys(richPros).length > 0 ? { pros: richPros } : {}),
		...(Object.keys(richProjects).length > 0
			? { projects: richProjects }
			: {}),
		...(Object.keys(richRooms).length > 0 ? { rooms: richRooms } : {}),
		...(Object.keys(richBlogs).length > 0
			? { blogs: richBlogs }
			: {}),
	};
 
	return { results: enrichedResults, richData };
}
 
export default search;