// src/lib/session.ts
import { dayjs } from "@mesob/common";
import { nanoid } from "nanoid";
var generateHandle = () => {
  return nanoid(10);
};
var getSessionExpiresAt = (days = 30) => dayjs().add(days, "day").toISOString();
var parseDuration = (duration) => {
  const match = duration.match(/^(\d+)([smhd])$/);
  if (!(match?.[1] && match[2])) {
    throw new Error(`Invalid duration format: ${duration}`);
  }
  const value = Number.parseInt(match[1], 10);
  const unit = match[2];
  const multipliers = {
    s: 1,
    m: 60,
    h: 3600,
    d: 86400
  };
  return value * (multipliers[unit] || 1);
};
var addDuration = (duration) => {
  const seconds = parseDuration(duration);
  return dayjs().add(seconds, "second").toISOString();
};
var generateOtpCode = (length = 6) => {
  const digits = "0123456789";
  const maxValid = 250;
  let code = "";
  while (code.length < length) {
    const randomValues = new Uint8Array(length - code.length);
    crypto.getRandomValues(randomValues);
    for (const val of randomValues) {
      if (val < maxValid && code.length < length) {
        code += digits[val % 10];
      }
    }
  }
  return code;
};
var getSessionDuration = ({
  sessionConfig,
  rememberMe
}) => {
  if (rememberMe) {
    return sessionConfig.rememberMeExpiresIn;
  }
  return sessionConfig.shortSessionExpiresIn;
};
var getSessionUpdateAge = ({
  sessionConfig,
  rememberMe
}) => {
  if (rememberMe) {
    return sessionConfig.updateAge;
  }
  return sessionConfig.shortSessionUpdateAge;
};
var shouldRefreshSession = ({
  expiresAt,
  updateAge
}) => {
  const updateAgeSeconds = parseDuration(updateAge);
  const now = dayjs();
  const expires = dayjs(expiresAt);
  const remainingSeconds = expires.diff(now, "second");
  return remainingSeconds > 0 && remainingSeconds <= updateAgeSeconds;
};
var getRefreshedExpiresAt = ({
  sessionConfig,
  rememberMe
}) => {
  const duration = getSessionDuration({ sessionConfig, rememberMe });
  return addDuration(duration);
};
var isSessionExpired = (expiresAt) => {
  return dayjs(expiresAt).isBefore(dayjs());
};
export {
  addDuration,
  generateHandle,
  generateOtpCode,
  getRefreshedExpiresAt,
  getSessionDuration,
  getSessionExpiresAt,
  getSessionUpdateAge,
  isSessionExpired,
  parseDuration,
  shouldRefreshSession
};
//# sourceMappingURL=session.js.map