import { getMailConnections, getMailBlockedStats } from "../../db/mail";
import { resolveProviderMeta } from "../../utils/imap-providers";

/**
 * GET /api/mail/status
 * Gibt den Verbindungsstatus + Statistiken zurück.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);

  const connections = await getMailConnections(user.id);

  const list = connections.map((c) => {
    const providerMeta = resolveProviderMeta(c.imapHost);
    return {
      id: c.id,
      email: c.email,
      title: c.title ?? null,
      provider: providerMeta.provider,
      providerLabel: providerMeta.providerLabel,
      isCustomDomain: providerMeta.isCustomDomain,
      isActive: c.isActive,
      lastScannedAt: c.lastScannedAt?.toISOString() ?? null,
      nextScanAt: c.nextScanAt?.toISOString() ?? null,
      totalBlocked: c.emailsBlocked,
      totalScanned: c.emailsScanned,
      scanInterval: c.scanInterval,
      blockRate:
        c.emailsScanned > 0
          ? Math.round((c.emailsBlocked / c.emailsScanned) * 100)
          : 0,
      lastConnectError: c.lastConnectError ?? null,
      lastConnectErrorAt: c.lastConnectErrorAt?.toISOString() ?? null,
      lastIdleHeartbeatAt: c.lastIdleHeartbeatAt?.toISOString() ?? null,
    };
  });

  const blocked7d = await getMailBlockedStats(user.id);

  const dailyMap: Record<string, number> = {};
  for (const row of blocked7d) {
    const day = row.createdAt.toISOString().slice(0, 10);
    dailyMap[day] = (dailyMap[day] ?? 0) + 1;
  }
  const dailyStats = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(Date.now() - (6 - i) * 86_400_000);
    const key = d.toISOString().slice(0, 10);
    return {
      date: key,
      label: d.toLocaleDateString("de-DE", { weekday: "short" }),
      count: dailyMap[key] ?? 0,
    };
  });

  return {
    connected: list.length > 0,
    accounts: list,
    totalBlocked: list.reduce((s, c) => s + c.totalBlocked, 0),
    totalScanned: list.reduce((s, c) => s + c.totalScanned, 0),
    dailyStats,
  };
});
