import { randomBytes } from "crypto";
import { getMailConnections, upsertImapProxyAccount } from "../../db/mail";
import { getProfile } from "../../db/profile";
import { getPlanLimits } from "../../utils/plan-features";
import { encrypt } from "../../utils/crypto";
import { detectSmtpProvider } from "../../utils/imap-providers";

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);

  const profile = await getProfile(user.id);
  const limits = getPlanLimits(profile?.plan ?? "free");
  if (limits.mailAgents !== Infinity) {
    throw createError({ statusCode: 403, message: "Nur für Legend-User verfügbar" });
  }

  const connections = await getMailConnections(user.id);
  if (connections.length === 0) {
    throw createError({
      statusCode: 400,
      message: "Erst eine E-Mail-Verbindung herstellen",
    });
  }

  const results = await Promise.all(
    connections.map(async (connection) => {
      const plainPassword = randomBytes(12).toString("base64url");
      const localPart = connection.email.replace("@", ".").replace(/[^a-z0-9._-]/gi, "-");
      const proxyUsername = `${localPart}@imap.rebreak.org`;

      await upsertImapProxyAccount({
        userId: user.id,
        proxyUsername,
        proxyPassword: encrypt(plainPassword),
        connectionId: connection.id,
      });

      const smtp = detectSmtpProvider(connection.imapHost);
      return {
        username: proxyUsername,
        password: plainPassword,
        realEmail: connection.email,
        host: "imap.rebreak.org",
        port: 993,
        smtpHost: smtp.host,
        smtpPort: smtp.port,
      };
    }),
  );

  return {
    note: "Passwörter werden nur einmal angezeigt – sofort in iOS Mail eintragen.",
    accounts: results,
  };
});
