import { rm } from 'node:fs/promises'
import path from 'node:path'
import { existsSync } from 'node:fs'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

function resolvePluginRoot(frontendRoot: string): string {
  const pluginRoot = path.resolve(frontendRoot, '..', '..');

  if (existsSync(path.join(pluginRoot, 'actionpanel-ai.php'))) {
    return pluginRoot;
  }

  throw new Error('Unable to locate the WordPress plugin root for the frontend snapshot build.');
}

function pluginBuildCleanup(outDir: string) {
  return {
    name: 'actionpanel-ai-build-cleanup',
    closeBundle: async () => {
      await Promise.all([
        rm(path.join(outDir, 'index.html'), { force: true }),
      ]);
    },
  };
}

export default defineConfig(() => {
  const frontendRoot = process.cwd();
  const pluginRoot = resolvePluginRoot(frontendRoot);
  const outDir = path.join(pluginRoot, 'build');

  return {
    base: './',
    publicDir: false,
    plugins: [react(), pluginBuildCleanup(outDir)],
    build: {
      outDir,
      emptyOutDir: true,
      cssCodeSplit: false,
      rollupOptions: {
        output: {
          entryFileNames: 'index.js',
          chunkFileNames: 'chunks/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            if (assetInfo.name && assetInfo.name.endsWith('.css')) {
              return 'index.css';
            }
            return 'assets/[name]-[hash][extname]';
          },
        },
      },
      minify: 'terser',
      terserOptions: {
        mangle: {
          reserved: [ 'wp' ],
        },
      },
    },
    define: {
      'import.meta.env.VITE_TARGET': JSON.stringify('wordpress'),
      'import.meta.env.VITE_DEPLOYMENT': JSON.stringify('production'),
    },
  }
})
