'use strict';

/**
 * Server-side local-date helpers.
 *
 * Bill due dates and payment dates are stored as plain YYYY-MM-DD strings in
 * the server's local timezone (the client computes "today" the same way in
 * client/pages/TrackerPage.jsx → localDateString). Never derive a calendar
 * date from Date.toISOString() — that yields the UTC date, which disagrees
 * with local time around midnight and month boundaries.
 */

/** YYYY-MM-DD in local time. */
function localDateString(date = new Date()) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/** { year, month } (1-based month) in local time. */
function localYearMonth(date = new Date()) {
  return { year: date.getFullYear(), month: date.getMonth() + 1 };
}

/** YYYY-MM-DD in local time, `days` days before `from`. */
function localDateStringDaysAgo(days, from = new Date()) {
  const d = new Date(from);
  d.setDate(d.getDate() - days);
  return localDateString(d);
}

/** Today as YYYY-MM-DD in local time. Alias of localDateString(). */
function todayLocal() {
  return localDateString(new Date());
}

/** YYYY-MM month key in local time (e.g. "2026-06"). */
function monthKey(date = new Date()) {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
}

module.exports = { localDateString, localYearMonth, localDateStringDaysAgo, todayLocal, monthKey };
