import User from "../models/user";

// Non-prod safety: when OUTBOUND_CUTOFF (ISO date) is set, users created before
// it are treated as restored production data and never receive emails, push
// notifications or SMS. Users created after the cutoff are notified normally.
// Leave OUTBOUND_CUTOFF unset in production.
const cutoff = process.env.OUTBOUND_CUTOFF
  ? new Date(process.env.OUTBOUND_CUTOFF)
  : null;

export const outboundCutoff = cutoff && !isNaN(cutoff.getTime()) ? cutoff : null;

export function isLegacyUser(user: any): boolean {
  if (!outboundCutoff || !user) return false;
  const createdAt = user.createdAt ? new Date(user.createdAt) : null;
  return !createdAt || createdAt < outboundCutoff;
}

export async function isLegacyEmail(email: string): Promise<boolean> {
  if (!outboundCutoff) return false;
  const escaped = email.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  const user = await User.findOne({
    email: new RegExp(`^${escaped}$`, "i"),
  }).select("createdAt");
  return isLegacyUser(user);
}
