import { Types } from "mongoose";
import { OtpModel } from "../models/OtpModel";
import { AUTH_CONSTANTS } from "../constants/messages";
import { otpExpiresAt, OtpSendReason } from "../constants/otp";

export async function saveOtpForUser(
  userId: unknown,
  code: number,
  reason: OtpSendReason,
) {
  return OtpModel.findOneAndUpdate(
    { userId },
    { otp: String(code), expiry: otpExpiresAt(), reason },
    { upsert: true, new: true },
  );
}

export async function assertOtpValid(userId: Types.ObjectId, otp: string) {
  const otpRes = await OtpModel.findOne({ userId });
  if (!otpRes) {
    return { ok: false as const, message: AUTH_CONSTANTS.OTP_NOT_FOUND };
  }
  if (new Date() > otpRes.expiry) {
    return { ok: false as const, message: AUTH_CONSTANTS.OTP_EXPIRED };
  }
  if (String(otpRes.otp).trim() !== String(otp).trim()) {
    return { ok: false as const, message: AUTH_CONSTANTS.OTP_MISMATCH };
  }
  return { ok: true as const, otpRes };
}

export async function clearOtpsForUser(userId: Types.ObjectId) {
  return OtpModel.deleteMany({ userId });
}
