import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';

export default defineConfig({
  define: { ABECE_BOOKING_PREMIUM: JSON.stringify(process.env.ABECE_BOOKING_BUILD_EDITION !== 'lite') },
  build: {
    outDir: 'assets/build',
    emptyOutDir: true,
    lib: {
      entry: fileURLToPath(new URL('./admin-ui/index.tsx', import.meta.url)),
      name: 'ABeCeBookingAdmin',
      formats: ['iife'],
      cssFileName: 'calendar',
      fileName: () => 'admin.js',
    },
    rollupOptions: {
      external: ['react', 'react-dom/client', '@wordpress/i18n'],
      output: {
        globals: {
          react: 'wp.element',
          'react-dom/client': 'wp.element',
          '@wordpress/i18n': 'wp.i18n',
        },
      },
    },
  },
  plugins: [{
    name: 'wordpress-asset-metadata',
    generateBundle: {
      order: 'post',
      handler(_options, bundle) {
        const entry = bundle['admin.js'];
        if (!entry || entry.type !== 'chunk') throw new Error('Missing admin entry');
        const hash = createHash('sha256').update(entry.code);
        for (const item of Object.values(bundle)) {
          if (item.type === 'asset' && item.fileName.endsWith('.css')) hash.update(item.source);
        }
        const version = hash.digest('hex').slice(0, 16);
        this.emitFile({
          type: 'asset',
          fileName: 'admin.asset.php',
          source: `<?php\nreturn ['dependencies' => ['wp-element', 'wp-i18n'], 'version' => '${version}'];\n`,
        });
      },
    },
  }],
});
