export const MAX_TIMEOUT_MS = 28 * 24 * 60 * 60 * 1000;

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

export function parseDuration(input: string): number {
  const m = input.match(/^(\d+)([smhd])$/i);
  if (!m) {
    throw new DurationParseError('Duration must be like 30m, 12h, 7d');
  }
  const amount = Number(m[1]);
  const unit = m[2]!.toLowerCase();
  const factor = unit === 's' ? 1000 : unit === 'm' ? 60000 : unit === 'h' ? 3600000 : 86400000;
  return amount * factor;
}

/** Parse a duration and enforce Discord's 28-day timeout maximum. */
export function parseTimeoutDuration(input: string): number {
  const ms = parseDuration(input);
  if (ms <= 0) {
    throw new DurationParseError('Duration must be positive');
  }
  if (ms > MAX_TIMEOUT_MS) {
    throw new DurationParseError('Timeout duration cannot exceed 28 days');
  }
  return ms;
}

export function tryParseDuration(input: string): number | null {
  try {
    return parseDuration(input);
  } catch {
    return null;
  }
}
