#include <cstdio>
#include <optional>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utils/parse_duration.hpp>

namespace utils {

// Strongly inspired from prosody
// https://hg.prosody.im/trunk/file/0ff11f2e87cd/util/human/io.lua#l214
static const long day = 86400;

static const std::unordered_map<std::string, long> multipliers = {
    {"d", day}, {"w", day * 7}, {"mon", day * 31}, {"y", day * 365.2425},
    {"s", 1},   {"min", 60},    {"h", 3600},       {"ho", 3600},
};

std::optional<long> parse_duration(const std::string &duration) {
  std::size_t ptr;
  long number;
  try {
    number = std::stol(duration, &ptr, 10);
  } catch (std::invalid_argument &) {
    return {};
  }
  const std::string m = duration.substr(ptr);

  if (!multipliers.contains(m))
    return {};

  const long multiplier = multipliers.at(m);

  return multiplier * number;
}
} // namespace utils
