import { getProfile } from "../../db/profile";
import { getPlanLimits } from "../../utils/plan-features";
import { updateMailConnectionInterval } from "../../db/mail";

/**
 * PATCH /api/mail/interval
 * Body: { connectionId, interval: 1 | 8 | 24 }
 * Setzt das Scan-Intervall für eine Mail-Verbindung.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const { connectionId, interval } = (await readBody(event)) as {
    connectionId: string;
    interval: number;
  };

  if (!connectionId || !Number.isInteger(interval) || interval < 1) {
    throw createError({
      statusCode: 400,
      message: "connectionId und interval erforderlich",
    });
  }

  // Plan-Limit: erlaubte Intervalle prüfen
  const profile = await getProfile(user.id);
  const limits = getPlanLimits(profile?.plan ?? "free");

  if (!limits.mailIntervalOptions.includes(interval)) {
    throw createError({
      statusCode: 403,
      message: `Dein Plan erlaubt nur folgende Intervalle (Stunden): ${limits.mailIntervalOptions.join(", ")}`,
    });
  }

  await updateMailConnectionInterval(user.id, connectionId, interval);

  return { ok: true, interval };
});
