import crypto from "crypto";
import { prisma } from "@/lib/prisma";
import { resolveMailSetting, sendMail } from "@/lib/notify";

/* Best-effort platform email delivery for central (super-admin) messages.
   Every send resolves the institution's own SMTP row first and falls back
   to the central one, and never throws into the caller's flow — a failed
   email must not roll back a payment, registration or demo grant. */

/** Send through the institution's active mail setting, else the central one. */
export async function sendCentralMail(opts: {
  to: string;
  subject: string;
  html: string;
  text: string;
  institutionId?: number | null;
}): Promise<boolean> {
  try {
    const resolved = await resolveMailSetting(opts.institutionId ?? null);
    if (!resolved) return false;
    await sendMail(resolved.setting, {
      to: opts.to,
      subject: opts.subject,
      html: opts.html,
      text: opts.text,
    });
    return true;
  } catch (err) {
    console.error("central-mail-failed", err);
    return false;
  }
}

/** First institution admin with a login email (the billing/credential recipient). */
export async function institutionAdmin(
  institutionId: number
): Promise<{ email: string; name: string } | null> {
  const admin = await prisma.user.findFirst({
    where: { institutionId, role: "INSTITUTION_ADMIN", email: { not: null } },
    orderBy: { id: "asc" },
    select: { email: true, name: true },
  });
  return admin ? { email: admin.email as string, name: admin.name } : null;
}

/** Readable, copy-friendly password for credential emails (no 0/O/1/l). */
export function generatePassword(length = 10): string {
  const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789@#$%";
  let out = "";
  const bytes = crypto.randomBytes(length);
  for (let i = 0; i < length; i++) out += alphabet[bytes[i] % alphabet.length];
  return out;
}
