/**
 * SQLite-friendly timestamp normalization.
 *
 * SQLite's `datetime('now')` returns "2026-05-19 18:30:00" — UTC, but no
 * timezone marker. When that string lands in JavaScript:
 *   new Date('2026-05-19 18:30:00')   // parsed as LOCAL time (wrong)
 *
 * Browsers shift the displayed value by the user's offset — a UTC 18:30
 * looks like 18:30 in their local clock if treated as local, hours off
 * from the real moment. Frontend Date.toLocaleString() then renders the
 * wrong number.
 *
 * Append a 'Z' so JS treats it as UTC, and Date.toLocaleString() will
 * automatically convert to the user's local timezone.
 *
 * Idempotent: if the string already has a 'Z' or a numeric offset, or
 * is already in ISO 8601 (T separator), it's returned unchanged.
 */
export function toIsoUTC(s: string | null | undefined): string | null {
  if (!s) return null;
  // Already ISO with T separator → just ensure it has a TZ marker.
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(s)) {
    return /Z$|[+-]\d{2}:?\d{2}$/.test(s) ? s : s + 'Z';
  }
  // SQLite datetime('now') shape: "YYYY-MM-DD HH:MM:SS"
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?$/.test(s)) {
    return s.replace(' ', 'T') + 'Z';
  }
  return s;
}
