/** OTP validity (registration, resend, forgot_password) — keep in sync across auth + gas-station flows */
export const OTP_EXPIRY_MS = 10 * 60 * 1000;

export function otpExpiresAt(): Date {
  return new Date(Date.now() + OTP_EXPIRY_MS);
}

/** Allowed `reason` for POST /auth/send-otp — drives email template copy. */
export const OTP_SEND_REASON = {
  REGISTRATION: "registration",
  PASSWORD_RESET: "password_reset",
  FORGOT_PASSWORD: "forgot_password",
} as const;

export type OtpSendReason = (typeof OTP_SEND_REASON)[keyof typeof OTP_SEND_REASON];

export const OTP_SEND_REASON_ZOD = [
  OTP_SEND_REASON.REGISTRATION,
  OTP_SEND_REASON.PASSWORD_RESET,
  OTP_SEND_REASON.FORGOT_PASSWORD,
] as const;

export function isOtpRegistrationEmailReason(reason: string): boolean {
  return reason === OTP_SEND_REASON.REGISTRATION;
}

export function isOtpPasswordResetEmailReason(reason: string): boolean {
  return (
    reason === OTP_SEND_REASON.PASSWORD_RESET ||
    reason === OTP_SEND_REASON.FORGOT_PASSWORD
  );
}

/** Resolve OTP flow from DB reason; legacy rows without reason use user.isVerified. */
export function resolveOtpPurpose(
  storedReason: string | undefined | null,
  userIsVerified: boolean,
): OtpSendReason {
  if (storedReason && OTP_SEND_REASON_ZOD.includes(storedReason as OtpSendReason)) {
    return storedReason as OtpSendReason;
  }
  return userIsVerified
    ? OTP_SEND_REASON.FORGOT_PASSWORD
    : OTP_SEND_REASON.REGISTRATION;
}
