const MS_PER_UNIT: Record<string, number> = {
  ms: 1,
  s: 1000,
  m: 60_000,
  h: 3_600_000,
  d: 86_400_000,
  w: 7 * 86_400_000,
  y: 365 * 86_400_000,
};

/** Parse jsonwebtoken-style durations (e.g. 15m, 30d, or seconds as plain number). */
export function jwtDurationToMs(value: string): number {
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error('JWT duration must not be empty');
  }

  if (/^\d+$/.test(trimmed)) {
    return parseInt(trimmed, 10) * 1000;
  }

  const match = trimmed.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d|w|y)?$/i);
  if (!match) {
    throw new Error(`Invalid JWT duration: "${value}"`);
  }

  const amount = parseFloat(match[1]);
  const unit = (match[2] ?? 's').toLowerCase();
  const multiplier = MS_PER_UNIT[unit];
  if (!multiplier) {
    throw new Error(`Invalid JWT duration unit in "${value}"`);
  }

  return amount * multiplier;
}

export function sessionExpiresAtFromNow(refreshExpiresIn: string): Date {
  return new Date(Date.now() + jwtDurationToMs(refreshExpiresIn));
}
