import path from 'path';
import fs from 'fs';

async function handler(req, res) {
  try {
    const assetsDir = path.join(process.cwd(), "public", "assets");
    const files = fs.readdirSync(assetsDir);
    const packageFiles = files.filter((f) => f.startsWith("cloudvault-server-") && f.endsWith(".tar.gz"));
    if (packageFiles.length === 0) {
      return res.status(404).json({ error: "No package found" });
    }
    packageFiles.sort();
    const latestPackage = packageFiles[packageFiles.length - 1];
    const packagePath = path.join(assetsDir, latestPackage);
    if (!fs.existsSync(packagePath)) {
      return res.status(404).json({ error: "Package file not found" });
    }
    const stats = fs.statSync(packagePath);
    res.setHeader("Content-Type", "application/gzip");
    res.setHeader("Content-Disposition", `attachment; filename="${latestPackage}"`);
    res.setHeader("Content-Length", stats.size);
    const fileStream = fs.createReadStream(packagePath);
    fileStream.pipe(res);
  } catch (error) {
    console.error("Download error:", error);
    res.status(500).json({ error: "Failed to download package", message: String(error) });
  }
}

export { handler as h };
