import vue from '@vitejs/plugin-vue';
import path from 'path';

const I18N_PASS = process.env.FMT_I18N === '1';

const wrapEntriesInIIFE = () => ({
  name: 'wrap-entries-iife',
  generateBundle(options, bundle) {
    for (const chunk of Object.values(bundle)) {
      if (chunk.type !== 'chunk' || !chunk.isEntry) {
        continue;
      }

      if (/^\s*import[\s{("']/.test(chunk.code)) {
        continue;
      }

      chunk.code = `(function(){\n${chunk.code}\n})();`;
    }
  }
});

export const createFormatricaViteConfig = ({
  adminEntry,
  definitions,
  frontendEntry,
  outputDir
}) => ({
  plugins: [vue(), wrapEntriesInIIFE()],
  define: Object.fromEntries(
    Object.entries(definitions).map(([name, value]) => [name, JSON.stringify(value)])
  ),
  base: './',
  build: {
    outDir: I18N_PASS ? 'i18n-build' : outputDir,
    emptyOutDir: true,
    minify: I18N_PASS ? false : 'esbuild',
    manifest: !I18N_PASS,
    rollupOptions: {
      treeshake: {
        manualPureFunctions: ['__']
      },
      input: {
        admin: path.resolve(__dirname, adminEntry),
        frontend: path.resolve(__dirname, frontendEntry),
        block: path.resolve(__dirname, 'src/block/index.js'),
        'friendly-captcha': path.resolve(__dirname, 'src/vendor/friendly-captcha.js')
      },
      preserveEntrySignatures: 'strict',
      external: [
        '@wordpress/blocks',
        '@wordpress/components',
        '@wordpress/data',
        '@wordpress/element',
        '@wordpress/i18n',
        '@wordpress/block-editor'
      ],
      output: {
        entryFileNames: 'js/[name].js',
        chunkFileNames: 'js/[name]-[hash].js',
        assetFileNames: ({ name }) => {
          if (!name) {
            return 'assets/[name]-[hash][extname]';
          }

          const ext = path.extname(name);

          if (ext === '.css' || name.endsWith('css')) {
            const base = ext ? path.basename(name, ext) : name;
            const safeExt = ext || '.css';
            return `css/${base}-[hash]${safeExt}`;
          }

          return 'assets/[name]-[hash][extname]';
        },
        globals: {
          '@wordpress/blocks': 'wp.blocks',
          '@wordpress/components': 'wp.components',
          '@wordpress/data': 'wp.data',
          '@wordpress/element': 'wp.element',
          '@wordpress/i18n': 'wp.i18n',
          '@wordpress/block-editor': 'wp.blockEditor'
        }
      }
    }
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
});
