import fs from "fs";
import fse from "fs-extra";
import path, { resolve } from "path";
import { defineConfig } from "vite";
import pkg from "./package.json";
import mnf from "./public/manifest.json";

export default defineConfig({
  plugins: [
    {
      name: "copy-content-script",
      closeBundle: async () => {
        const src = resolve(__dirname, "dist-content/content/content.js");
        const destDir = resolve(
          __dirname,
          `${pkg.name}_${mnf.version}`,
          "content"
        );
        const dest = resolve(destDir, "content.js");

        if (!fs.existsSync(src)) {
          console.warn(
            "⚠️  content.js chưa được build từ vite.config.content.ts"
          );
          return;
        }

        await fse.ensureDir(destDir);
        await fse.copyFile(src, dest);
        console.log(`✅ Copied content.js → ${dest}`);
      },
    },
    {
      name: "copy-release-folder",
      closeBundle: async () => {
        const buildDir = resolve(__dirname, `${pkg.name}_${mnf.version}`);
        const releaseDir = resolve(
          __dirname,
          "releases",
          `${pkg.name}_${mnf.version}`
        );

        if (!fs.existsSync(buildDir)) {
          console.warn("⚠️ Build folder chưa được tạo:", buildDir);
          return;
        }

        await fse.ensureDir(path.dirname(releaseDir));
        await fse.copy(buildDir, releaseDir, { overwrite: true });
        console.log(`📦 Copied ${buildDir} → ${releaseDir}`);
      },
    },
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});
