const parseDateOnly = (dateInput) => {
  if (!dateInput) return null;
  const str = typeof dateInput === 'string' ? dateInput.split('T')[0] : dateInput.toISOString().split('T')[0];
  const [year, month, day] = str.split('-').map(Number);

  if (!year || !month || !day) {
    return null;
  }

  return new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));
};

const getDateRange = (period) => {
  const now = new Date();
  const end = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999));
  const start = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0));

  if (period === 'weekly') {
    start.setUTCDate(start.getUTCDate() - 6);
  } else if (period === 'monthly') {
    start.setUTCDate(start.getUTCDate() - 29);
  }

  return { start, end };
};

module.exports = { parseDateOnly, getDateRange };
