export function healthEventFingerprint(event = {}) { return [ event.eventType, event.ruleId ?? '', event.metricType ?? '', event.symptomCode ?? '', ].join('|'); } export function mapPgHealthEventRow(row, userId) { const parseJson = (value, fallback = []) => { if (value == null) return fallback; if (typeof value === 'object') return value; try { return JSON.parse(String(value)); } catch { return fallback; } }; return { id: Number(row.id), userId: String(userId), eventType: row.event_type, severity: row.severity, detectedAt: row.detected_at ? new Date(row.detected_at).getTime() : Date.now(), ruleId: row.rule_id ?? null, metricsInvolved: parseJson(row.metrics_involved), evidenceObservationIds: parseJson(row.evidence_observation_ids), agentSummary: row.agent_summary ?? null, status: row.status ?? 'open', message: row.agent_summary ?? null, metricType: parseJson(row.metrics_involved)[0]?.metricType ?? null, symptomCode: parseJson(row.metrics_involved)[0]?.symptomCode ?? null, createdAt: row.created_at ? new Date(row.created_at).getTime() : Date.now(), }; } export function mapHealthEventToPgPayload(event, now = Date.now()) { const metricsInvolved = []; if (event.metricType) { metricsInvolved.push({ metricType: event.metricType, symptomCode: event.symptomCode ?? null, value: event.value ?? null, baselineMean: event.baselineMean ?? null, }); } return { event_type: event.eventType, severity: event.severity, detected_at: new Date(event.createdAt ?? event.detectedAt ?? now).toISOString(), rule_id: event.ruleId ?? null, metrics_involved: JSON.stringify(metricsInvolved), evidence_observation_ids: JSON.stringify(event.evidenceObservationIds ?? []), agent_summary: event.message ?? event.agentSummary ?? null, status: 'open', }; }