/**
 * Range helpers — calendar-module.
 *
 * `parseRange` validates ISO date/datetime strings and enforces a 92-day cap
 * to bound query cost on the events aggregate endpoint.
 */

const MAX_RANGE_DAYS = 92
const MS_PER_DAY = 86_400_000

export class RangeError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'CalendarRangeError'
  }
}

/**
 * Parse and validate a calendar range.
 *
 * @throws {RangeError} if start/end are not valid ISO strings, end < start, or
 *   the span exceeds 92 days.
 */
export function parseRange(start: string, end: string): { start: Date; end: Date } {
  const startDate = new Date(start)
  const endDate = new Date(end)

  if (isNaN(startDate.getTime())) {
    throw new RangeError(`Invalid start date: ${start}`)
  }
  if (isNaN(endDate.getTime())) {
    throw new RangeError(`Invalid end date: ${end}`)
  }
  if (endDate < startDate) {
    throw new RangeError('end must be >= start')
  }

  const spanDays = (endDate.getTime() - startDate.getTime()) / MS_PER_DAY
  if (spanDays > MAX_RANGE_DAYS) {
    throw new RangeError(`Range must not exceed ${MAX_RANGE_DAYS} days (requested ${Math.ceil(spanDays)})`)
  }

  return { start: startDate, end: endDate }
}
