/**
 * What the two bundle configs agree on.
 *
 * Both are IIFE bundles written straight into the folders the PHP enqueues
 * from, with no manifest and no hashed filename: WordPress cache-busts by
 * `filemtime()` on the file itself (see Razorbooking_Admin::enqueue_scripts),
 * so a stable name is the contract, not an oversight.
 */

import { resolve } from 'node:path';
import type { UserConfig } from 'vite';

/** Where each bare import lands on the global object at runtime. */
export const WP_GLOBALS: Record< string, string > = {
	react: 'wp.element',
	'react-dom': 'wp.element',
	'react-dom/client': 'wp.element',
	'@wordpress/element': 'wp.element',
	'@wordpress/i18n': 'wp.i18n',
	'@wordpress/blocks': 'wp.blocks',
	'@wordpress/block-editor': 'wp.blockEditor',
	'@wordpress/components': 'wp.components',
	'@wordpress/server-side-render': 'wp.serverSideRender',
	'@wordpress/data': 'wp.data',
};

export function base( root: string ): UserConfig {
	return {
		root,
		// The plugin's public/ folder is PHP; Vite would otherwise copy it into admin/js/.
		publicDir: false,
		esbuild: {
			jsx: 'automatic',
			// Not a source-of-truth claim about which React is running — see
			// src/shims/jsx-runtime.ts for why the runtime is re-implemented.
			jsxImportSource: 'react',
		},
		resolve: {
			// Ordered: the exact `@/design-system` (the barrel synced admin
			// features import) must match before the `@` prefix. Mirrored in
			// tsconfig.json `paths`.
			alias: [
				{ find: 'react/jsx-runtime', replacement: resolve( root, 'src/shims/jsx-runtime.ts' ) },
				{ find: /^@\/design-system$/, replacement: resolve( root, 'src/admin/ds.ts' ) },
				{ find: '@', replacement: resolve( root, 'src/admin' ) },
			],
		},
		define: {
			// Bundled code that branches on it (none of ours, but a dependency
			// might) takes the production path.
			'process.env.NODE_ENV': JSON.stringify( 'production' ),
		},
	};
}

/** Rollup's half of the externals arrangement. */
export function externals() {
	return {
		external: Object.keys( WP_GLOBALS ),
		output: { globals: WP_GLOBALS },
	};
}
