export type SupportedTimeRange = '24hr' | '1week' | '1month'; const SUPPORTED_RANGES: SupportedTimeRange[] = ['24hr', '1week', '1month']; export function isSupportedTimeRange(value: unknown): value is SupportedTimeRange { return typeof value === 'string' && SUPPORTED_RANGES.includes(value as SupportedTimeRange); } export function toIsoDateTime(input: string): string { const parsedDate = new Date(input); if (Number.isNaN(parsedDate.getTime())) { throw new Error(`Invalid datetime format: ${input}. Expected ISO datetime string.`); } return parsedDate.toISOString(); } export function normalizeGraphDateTime(dateTime: string, timeZone = 'UTC') { return { dateTime: toIsoDateTime(dateTime), timeZone, }; } export function resolveTimeRangeStart(range: SupportedTimeRange, now = new Date()): Date { const start = new Date(now); if (range === '24hr') { start.setHours(start.getHours() - 24); return start; } if (range === '1week') { start.setDate(start.getDate() - 7); return start; } start.setMonth(start.getMonth() - 1); return start; } export function buildReceivedDateFilter(params: { timeRange?: unknown; startDateTime?: unknown; endDateTime?: unknown }): string { const { timeRange, startDateTime, endDateTime } = params; const filters: string[] = []; if (typeof startDateTime === 'string' && startDateTime.length > 0) { filters.push(`receivedDateTime ge ${toIsoDateTime(startDateTime)}`); } if (typeof endDateTime === 'string' && endDateTime.length > 0) { filters.push(`receivedDateTime le ${toIsoDateTime(endDateTime)}`); } if (filters.length > 0) { return `?$filter=${filters.join(' and ')}`; } if (timeRange === undefined) { return ''; } if (!isSupportedTimeRange(timeRange)) { throw new Error('Invalid timeRange. Supported values: 24hr, 1week, 1month'); } const fromDate = resolveTimeRangeStart(timeRange).toISOString(); return `?$filter=receivedDateTime ge ${fromDate}`; }