export function toIsoSqlUTC(d: Date = new Date()): string {
  return d.toISOString().replace('T', ' ').replace('Z', '');
}

/**
 * Devuelve YYYY-MM-DD en UTC (útil para consultas por rango de fecha).
 */
export function ymdUTC(date: Date = new Date()): string {
  const yyyy = String(date.getUTCFullYear()).padStart(4, '0');
  const mm = String(date.getUTCMonth() + 1).padStart(2, '0');
  const dd = String(date.getUTCDate()).padStart(2, '0');
  return `${yyyy}-${mm}-${dd}`;
}

/**
 * Convierte un string de timestamp (ISO 8601 o SQLite "YYYY-MM-DD HH:MM:SS") a ISO-8601.
 * Si ya contiene 'T' se devuelve tal cual; si no, reemplaza espacio por 'T' y añade 'Z'.
 */
export function toIsoUTC(raw: string): string {
  const s = String(raw ?? '').trim();
  if (!s) return '';
  if (s.includes('T')) return s;
  return s.replace(' ', 'T') + 'Z';
}

/**
 * Formats a Date as YYYY-MM-DD in the given IANA timezone.
 */
export function ymdInTZ(d: Date, tz: string): string {
  const parts = new Intl.DateTimeFormat('en-GB', {
    timeZone: tz,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).formatToParts(d);
  const get = (t: string) => parts.find((p) => p.type === t)?.value || '';
  return `${get('year')}-${get('month')}-${get('day')}`;
}

export function normalizeTime(input: string | null | undefined): string | null {
  const s = (input ?? '').trim();
  const m = /^(\d{1,2}):(\d{1,2})$/.exec(s);
  if (!m) return null;
  const h = Number(m[1]);
  const min = Number(m[2]);
  if (!Number.isFinite(h) || !Number.isFinite(min)) return null;
  if (h < 0 || h > 23 || min < 0 || min > 59) return null;
  const hh = String(h).padStart(2, '0');
  const mm = String(min).padStart(2, '0');
  return `${hh}:${mm}`;
}
