// zipPlugin.js
import { resolve } from 'path';
import { createWriteStream } from 'fs';
import archiver from 'archiver';

export default function zipBuildPlugin() {
  let outDir = 'dist'; // 默认值

  return {
    name: 'zip-after-build',
    configResolved(resolvedConfig) {
      // 读取 Vite 配置中的 build.outDir
      outDir = resolvedConfig.build.outDir;
    },
    closeBundle: {
      sequential: true,
      async handler() {
        const outputDir = resolve(__dirname, outDir);
        const zipFilePath = resolve(__dirname, `${outDir}.zip`);

        // 创建文件输出流
        const output = createWriteStream(zipFilePath);
        const archive = archiver('zip', {
          zlib: { level: 9 } // 设置压缩等级
        });

        return new Promise((resolve, reject) => {
          output.on('close', () => {
            console.log(`打包完成，共 ${archive.pointer()} 字节`);
            resolve();
          });

          archive.on('warning', (err) => {
            if (err.code !== 'ENOENT') {
              reject(err);
            }
          });

          archive.on('error', (err) => {
            reject(err);
          });

          // 将归档数据管道化到文件
          archive.pipe(output);

          // 将 dist 文件夹及其内容都压缩进 zip
          archive.directory(outputDir, outDir);

          // 完成归档
          archive.finalize();
        });
      }
    }
  };
}
