import { getBlockedMailsByConnection } from "../../../db/mail";
import { resolveProviderMeta } from "../../../utils/imap-providers";

/**
 * GET /api/mail/stats/blocked-by-connection
 *
 * Verteilung blockierter Mails per MailConnection — Half-Donut-Chart-Datenquelle.
 *
 * Response: { connectionId, title, email, provider, providerLabel, isCustomDomain, count }[]
 *   — Sortiert nach count DESC.
 *   — Connections ohne blocked emails sind NICHT included.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);

  const rows = await getBlockedMailsByConnection(user.id);

  const data = rows.map((r) => {
    const meta = resolveProviderMeta(r.imapHost);
    return {
      connectionId: r.connectionId,
      title: r.title,
      email: r.email,
      provider: meta.provider,
      providerLabel: meta.providerLabel,
      isCustomDomain: meta.isCustomDomain,
      count: r.count,
    };
  });

  return { success: true, data };
});
