import { upsertBlocklistDomains } from "../../db/domains";

const HAGEZI_URL =
  "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/gambling.txt";

export default defineEventHandler(async () => {
  const raw = await $fetch<string>(HAGEZI_URL, { responseType: "text" });

  const domains = raw
    .split("\n")
    .map((l) => l.trim())
    .filter((l) => l.startsWith("||") && l.endsWith("^"))
    .map((l) => l.slice(2, -1).toLowerCase())
    .filter((d) => d.length > 0 && !d.includes("/") && d.includes("."));

  if (domains.length < 1000) {
    throw createError({
      statusCode: 500,
      message: `Zu wenige Domains (${domains.length}), möglicher Fetch-Fehler`,
    });
  }

  const processed = await upsertBlocklistDomains(
    domains.map((domain) => ({ domain, source: "hagezi" })),
  );

  return {
    success: true,
    total_fetched: domains.length,
    processed,
    timestamp: new Date().toISOString(),
  };
});
