import { Types } from "mongoose"; import { buildUserLookupByPhone } from "./iran-mobile"; import { UserDbService } from "src/users/entities/db-service/user.db.service"; import { collectUserIdVariants } from "./party-access-queries"; /** All Mongo user ids that may represent the same person (JWT sub + phone aliases). */ export async function resolveLinkedUserIdStrings( userDbService: UserDbService, actor: { sub?: string; username?: string }, ): Promise { const ids = new Set(); if (actor?.sub) ids.add(String(actor.sub)); if (actor?.username?.trim()) { const rows = await userDbService.findAllByPhone(actor.username); for (const row of rows) { const id = (row as { _id?: unknown })._id; if (id != null) ids.add(String(id)); } } return [...ids]; } export async function resolveLinkedUserIdVariants( userDbService: UserDbService, actor: { sub?: string; username?: string }, ): Promise { const strings = await resolveLinkedUserIdStrings(userDbService, actor); return collectUserIdVariants(...strings); } export function ownerUserIdMatchesActor( ownerUserId: unknown, linkedUserIdStrings: string[], ): boolean { if (ownerUserId == null || linkedUserIdStrings.length === 0) return false; const owner = String(ownerUserId); return linkedUserIdStrings.some((id) => id === owner); } export function buildOwnerUserIdAccessFilter( linkedUserIdVariants: unknown[], ): Record | null { if (!linkedUserIdVariants.length) return null; if (linkedUserIdVariants.length === 1) { return { "owner.userId": linkedUserIdVariants[0] }; } return { $or: linkedUserIdVariants.map((id) => ({ "owner.userId": id })), }; }