import { addHours, addMinutes, endOfDay, endOfWeek, set } from 'date-fns';

import { type MoodDurationPreset } from 'src/types/userMood';

const combineDateAndTime = (date: Date, time: Date) =>
  set(date, {
    hours: time.getHours(),
    minutes: time.getMinutes(),
    seconds: 0,
    milliseconds: 0,
  });

export const computeExpiresAt = (
  duration: MoodDurationPreset,
  customDate?: Date | null,
  customTime?: Date | null,
): string | null => {
  const now = new Date();
  switch (duration) {
    case '30m':
      return addMinutes(now, 30).toISOString();
    case '1h':
      return addHours(now, 1).toISOString();
    case '4h':
      return addHours(now, 4).toISOString();
    case 'today':
      return endOfDay(now).toISOString();
    case 'this_week':
      // Mon–Sun week: ends on Sunday (on a Sunday that's end of today).
      return endOfWeek(now, { weekStartsOn: 1 }).toISOString();
    case 'custom':
      return customDate && customTime
        ? combineDateAndTime(customDate, customTime).toISOString()
        : null;
  }
};
