import type { MatchDocument } from '../../global/database/schema'; export type MatchReferenceResult = | { kind: 'matched'; match: MatchDocument } | { kind: 'ambiguous'; titles: string[] } | { kind: 'not-found' }; export function resolveRecruitingMatchReference( reference: string, matches: MatchDocument[], ): MatchReferenceResult { const normalizedCode = normalizeShortCode(reference); const codeMatches = matches.filter( (match) => match.shortCode && normalizeShortCode(match.shortCode) === normalizedCode, ); if (codeMatches.length === 1) { return { kind: 'matched', match: codeMatches[0] }; } if (codeMatches.length > 1) { return { kind: 'ambiguous', titles: codeMatches.map((match) => match.title), }; } const normalizedReference = normalizeLookup(reference); const exactMatches = matches.filter( (match) => normalizeLookup(match.title) === normalizedReference, ); if (exactMatches.length === 1) { return { kind: 'matched', match: exactMatches[0] }; } if (exactMatches.length > 1) { return { kind: 'ambiguous', titles: exactMatches.map((match) => match.title), }; } const prefixMatches = matches.filter((match) => normalizeLookup(match.title).startsWith(normalizedReference), ); if (prefixMatches.length === 1) { return { kind: 'matched', match: prefixMatches[0] }; } if (prefixMatches.length > 1) { return { kind: 'ambiguous', titles: prefixMatches.map((match) => match.title), }; } return { kind: 'not-found' }; } function normalizeLookup(value: string): string { return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase(); } function normalizeShortCode(value: string): string { return value.normalize('NFC').trim().replace(/\s+/g, '').toUpperCase(); }