"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportToZip = exportToZip;
const path = require("path");
const fs = require("fs");
const archiver = require("archiver");
const mkdirp = require("mkdirp");
const rimraf = require("rimraf");
const uuid_1 = require("uuid");
const shared_1 = require("./shared");
async function exportToZip(options) {
    const { courseSlug, bucket, outDir } = options;
    // 1. Create temporary folder
    const tmpName = (0, uuid_1.v4)();
    const zipOutDir = path.join(outDir, tmpName);
    rimraf.sync(zipOutDir);
    mkdirp.sync(zipOutDir);
    // 2. Download all course files from bucket to temporary directory
    await (0, shared_1.downloadS3Folder)(bucket, `courses/${courseSlug}/`, zipOutDir);
    // 3. Create ZIP file
    const zipName = `${courseSlug}.zip`;
    const zipPath = path.join(outDir, zipName);
    // Remove existing zip file if it exists
    if (fs.existsSync(zipPath)) {
        fs.unlinkSync(zipPath);
    }
    const output = fs.createWriteStream(zipPath);
    const archive = archiver("zip", { zlib: { level: 9 } });
    return new Promise((resolve, reject) => {
        output.on("close", () => {
            console.log(`✅ ZIP export completed: ${archive.pointer()} total bytes`);
            // Clean up temporary directory
            rimraf.sync(zipOutDir);
            resolve(zipPath);
        });
        archive.on("error", (err) => {
            console.error("❌ ZIP creation error:", err);
            rimraf.sync(zipOutDir);
            reject(err);
        });
        archive.pipe(output);
        // Add all files from the temporary directory to the ZIP
        archive.directory(zipOutDir, false);
        archive.finalize();
    });
}
