import * as OTPAuthLib from "otpauth";
import { decrypt } from "./encryption";
import { config } from "../config/env";

export const OTPAuth = {
  verify(
    encryptedSecret: string,
    code: string,
  ): { valid: boolean; counter: number | null } {
    try {
      const secret = decrypt(encryptedSecret);
      const totp = new OTPAuthLib.TOTP({
        secret: OTPAuthLib.Secret.fromBase32(secret),
        algorithm: config.totp.algorithm,
        digits: config.totp.digits,
        period: config.totp.period,
      });
      const delta = totp.validate({ token: code, window: 1 });
      if (delta === null) {
        return { valid: false, counter: null };
      }
      const currentCounter = Math.floor(Date.now() / 1000 / config.totp.period);
      // Only advance counter for current or past codes, not future ones
      const counterDelta = Math.min(delta, 0);
      return { valid: true, counter: currentCounter + counterDelta };
    } catch (err) {
      console.error("TOTP verification error:", err);
      return { valid: false, counter: null };
    }
  },
};
