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

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const format = (query.format as string) ?? "hosts";

  const rows = await getActiveBlocklistDomains();
  const domainList = rows.map((d) => d.domain);

  let content = "";
  let filename = "rebreak-blocklist";
  const contentType = "text/plain";

  if (format === "hosts") {
    filename += ".hosts";
    content = `# Rebreak Gambling Blocklist\n# Generated: ${new Date().toISOString()}\n# Format: /etc/hosts\n\n`;
    content += domainList
      .map((d) => `0.0.0.0 ${d}\n0.0.0.0 www.${d}`)
      .join("\n");
  } else if (format === "ublock") {
    filename += ".txt";
    content = `! Rebreak Gambling Blocklist\n! Generated: ${new Date().toISOString()}\n! Expires: 1 day\n\n`;
    content += domainList.map((d) => `||${d}^`).join("\n");
  } else if (format === "dns") {
    filename += "-dns.txt";
    content = domainList.join("\n");
  } else {
    throw createError({
      statusCode: 400,
      message: "Invalid format. Use: hosts, ublock, dns",
    });
  }

  setHeader(event, "Content-Type", `${contentType}; charset=utf-8`);
  setHeader(event, "Content-Disposition", `attachment; filename="${filename}"`);
  setHeader(event, "Cache-Control", "public, max-age=3600");

  return content;
});
