import crypto from "crypto";
import { GiftVoucher } from "@/models/GiftVoucher";

function randomVoucherCode(): string {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  let out = "";
  for (let i = 0; i < 8; i++) out += chars[crypto.randomInt(chars.length)];
  return `GUTSCHEIN-${out}`;
}

export async function generateUniqueVoucherCode(): Promise<string> {
  let code = randomVoucherCode();
  while (await GiftVoucher.findOne({ code })) code = randomVoucherCode();
  return code;
}

const THREE_YEARS_MS = 3 * 365 * 24 * 60 * 60 * 1000;

export function defaultVoucherExpiry(from: Date = new Date()): Date {
  return new Date(from.getTime() + THREE_YEARS_MS);
}
