import fs from 'node:fs';
import path from 'node:path';

const src = path.resolve('node_modules/pdfjs-dist/build/pdf.worker.min.mjs');
const destDir = path.resolve('public/pdfjs-dist');
const destMjs = path.join(destDir, 'pdf.worker.min.mjs');
const destJs = path.join(destDir, 'pdf.worker.min.js');

try {
  fs.mkdirSync(destDir, { recursive: true });
  // 复制 .mjs
  fs.copyFileSync(src, destMjs);
  console.log(`[pdfjs-dist] Worker copied to: ${destMjs}`);

  // 同步生成 .js 文件以兼容部分服务器缺少 mjs MIME 的情况
  fs.copyFileSync(src, destJs);
  console.log(`[pdfjs-dist] Worker duplicated to: ${destJs}`);
} catch (err) {
  console.error('[pdfjs-dist] Failed to copy worker:', err);
  process.exitCode = 1;
}