import fs from "node:fs/promises";
import path from "node:path";
import { config } from "../config";
import { logger } from "../utils/logger";

export const generateTorrentFile = async (
  magnet: string,
  hash: string
): Promise<string> => {
  const targetPath = path.join(config.torrentArchiveDir, `${hash}.torrent`);
  const { default: WebTorrent } = await import("webtorrent");
  const client = new WebTorrent();

  return new Promise((resolve, reject) => {
    const torrent = client.add(magnet, { path: config.dataDir });
    const timeout = setTimeout(() => {
      client.destroy();
      reject(new Error("Metadata fetch timeout"));
    }, 120_000);

    torrent.on("metadata", async () => {
      clearTimeout(timeout);
      try {
        const buffer = torrent.torrentFile;
        await fs.writeFile(targetPath, buffer);
        resolve(targetPath);
      } catch (error) {
        reject(error);
      } finally {
        client.destroy();
      }
    });

    torrent.on("error", (error: unknown) => {
      logger.error({ error }, "Torrent metadata error");
      clearTimeout(timeout);
      client.destroy();
      reject(error);
    });
  });
};
