import { addDays, format, setHours, setMinutes, startOfDay } from 'date-fns'

function toLocalDateFromKey(dateKey) {
  return new Date(`${dateKey}T00:00:00`)
}

function applyTime(dateValue, time = '00:00') {
  const nextDate = new Date(dateValue)
  const [hours, minutes] = String(time).split(':').map((value) => Number(value))
  return setMinutes(setHours(nextDate, hours || 0), minutes || 0)
}

export function usePublicDateDefaults() {
  const stableTodayKey = useState('public-stable-today-key', () => format(new Date(), 'yyyy-MM-dd'))
  const baseDay = computed(() => startOfDay(toLocalDateFromKey(stableTodayKey.value)))

  function buildDate(offsetDays = 0) {
    return addDays(baseDay.value, offsetDays)
  }

  function buildDateTime(offsetDays = 0, time = '12:30') {
    return applyTime(buildDate(offsetDays), time)
  }

  return {
    stableTodayKey,
    baseDay,
    buildDate,
    buildDateTime,
  }
}
