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

/**
 * GET /api/mail/results
 * Gibt die letzten blockierten Gambling-Mails zurück (paginiert).
 *
 * Query params:
 *   page?     number   — Seite (default 1)
 *   provider? string   — Provider-Filter als Komma-separierte Slugs (z.B. "gmail,outlook").
 *                        Wird intern auf imapHost-Liste aufgelöst.
 *                        Mehrfach-Werte: ?provider=gmail,outlook ODER ?provider=gmail&provider=outlook
 *
 * Response-Shape pro Entry (results[]):
 *   { id, userId, connectionId, gmailMessageId, senderEmail, senderName, subject,
 *     receivedAt, action, createdAt,
 *     connection: { id, email, title, providerName, provider, providerLabel, isCustomDomain } }
 */

// Slug → imapHost Mapping (invers zu resolveProviderMeta)
const PROVIDER_SLUG_TO_HOST: Record<string, string> = {
  gmail:    "imap.gmail.com",
  outlook:  "outlook.office365.com",
  icloud:   "imap.mail.me.com",
  gmx:      "imap.gmx.net",
  webde:    "imap.web.de",
  yahoo:    "imap.mail.yahoo.com",
  tonline:  "secureimap.t-online.de",
  freenet:  "mx.freenet.de",
  posteo:   "posteo.de",
  ionos:    "imap.ionos.de",
};

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

  const query = getQuery(event);
  const page = Math.max(1, parseInt((query.page as string) || "1"));

  // Provider-Filter parsen: ?provider=gmail,outlook  oder  ?provider=gmail&provider=outlook
  const rawProvider = query.provider;
  let providerHosts: string[] | undefined;

  if (rawProvider) {
    const slugs = (Array.isArray(rawProvider) ? rawProvider : [rawProvider as string])
      .flatMap((s) => s.split(","))
      .map((s) => s.trim().toLowerCase())
      .filter(Boolean);

    if (slugs.length > 0) {
      const hosts = slugs.map((slug) => PROVIDER_SLUG_TO_HOST[slug]).filter(Boolean);
      if (hosts.length > 0) providerHosts = hosts;
      // Unbekannte Slugs → ignorieren (kein Fehler, gibt leere Ergebnisse für unbekannte Provider)
    }
  }

  await deleteOldMailBlocked(user.id);

  const { results, total, pages } = await getMailBlockedPaginated(
    user.id,
    page,
    20,
    providerHosts,
  );

  // Connection-Metadaten anreichern
  const enriched = results.map((r) => {
    const conn = r.connection;
    const providerMeta = conn ? resolveProviderMeta(conn.imapHost) : null;
    return {
      id: r.id,
      userId: r.userId,
      connectionId: r.connectionId,
      gmailMessageId: r.gmailMessageId,
      senderEmail: r.senderEmail,
      senderName: r.senderName,
      subject: r.subject,
      receivedAt: r.receivedAt,
      action: r.action,
      createdAt: r.createdAt,
      connection: conn
        ? {
            id: conn.id,
            email: conn.email,
            title: conn.title ?? null,
            providerName: conn.providerName,
            provider: providerMeta?.provider ?? "custom",
            providerLabel: providerMeta?.providerLabel ?? conn.providerName ?? conn.imapHost,
            isCustomDomain: providerMeta?.isCustomDomain ?? true,
          }
        : null,
    };
  });

  return { results: enriched, total, page, pages };
});
