import { toIsoSqlUTC } from '../../src/utils/datetime';

export function toIsoSql(d: Date = new Date()): string {
  return toIsoSqlUTC(d);
}

export { toIsoSqlUTC };

export function ymdInTZ(d: Date, tz: string = 'Europe/Madrid'): 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 addDaysToYMD(ymd: string, days: number, tz: string = 'Europe/Madrid'): string {
  const [Y, M, D] = ymd.split('-').map(n => parseInt(n, 10));
  const base = new Date(Date.UTC(Y, (M || 1) - 1, D || 1));
  base.setUTCDate(base.getUTCDate() + days);
  return ymdInTZ(base, tz);
}

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}`;
}

export function addDays(date: Date, days: number): Date {
  const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
  d.setUTCDate(d.getUTCDate() + days);
  return d;
}
