/**
 * Builds the settings screen into ../build as one classic script and one
 * stylesheet, each in two copies like the CookieYes admin app:
 *
 *   settings-app.min.js / .min.css  `vite build` (enqueued by default)
 *   settings-app.js / .css          `vite build --mode unminified` (enqueued
 *                                   with SCRIPT_DEBUG, and where translation
 *                                   tools find the __() calls)
 *
 * React is not bundled: `react`, `react-dom` and the JSX runtime resolve to
 * src/wordpress/, which hands the app and its libraries the copies WordPress
 * ships (the "react" and "react-dom" scripts). They are aliases rather than
 * externals because some libraries are CommonJS and require( 'react' ), which
 * an external would leave as a require() call the browser can't run.
 *
 * PHP enqueues them with the plugin version as the cache buster (see
 * WTOFE_Settings_App::enqueue_scripts()). `--mode development` (npm run dev)
 * rebuilds the unminified copy with source maps on every change.
 */
import { fileURLToPath, URL } from 'node:url';
import { defineConfig, type Plugin } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';

const src = ( path = '' ) => fileURLToPath( new URL( `./src/${ path }`, import.meta.url ) );

/**
 * WordPress packages the app takes from WordPress's own scripts instead of
 * bundling, by the global each script defines. PHP lists the matching script
 * handles as dependencies (WTOFE_Settings_App::enqueue_scripts()).
 */
const WORDPRESS_SCRIPTS = {
    '@wordpress/api-fetch': 'wp.apiFetch',
    '@wordpress/components': 'wp.components',
    // Only for mounting the app (createRoot() or, before WordPress 6.2, render()).
    '@wordpress/element': 'wp.element',
    '@wordpress/i18n': 'wp.i18n',
};

/**
 * WP-CLI's string extractor (`wp i18n make-pot`, which wordpress.org runs to
 * build language packs) can't parse a statement that starts with a variable
 * named `async` (`async = true;`, inside zod). Wrapped in parentheses it means
 * the same and parses, so the unminified bundle's __() calls get extracted.
 */
function parsableByWpCli(): Plugin {
    return {
        name: 'wtofe-parsable-by-wp-cli',
        // On the final code: the IIFE wrapper is only added after renderChunk.
        generateBundle( _options, bundle ) {
            Object.values( bundle ).forEach( ( file ) => {
                if ( 'chunk' === file.type ) {
                    file.code = file.code.replace( /^(\s*)async = (.+);$/gm, '$1(async = $2);' );
                }
            } );
        },
    };
}

export default defineConfig( ( { mode } ) => {
    const minified = 'production' === mode;
    const suffix   = minified ? '.min' : '';

    return {
        plugins: [ react(), tailwindcss(), ! minified && parsableByWpCli() ],
        resolve: {
            alias: [
                { find: /^react$/, replacement: src( 'wordpress/react.ts' ) },
                { find: /^react\/jsx-(dev-)?runtime$/, replacement: src( 'wordpress/jsx-runtime.ts' ) },
                { find: /^react-dom$/, replacement: src( 'wordpress/react-dom.ts' ) },
                { find: /^@\//, replacement: src() },
            ],
        },
        define: {
            'process.env.NODE_ENV': JSON.stringify( 'development' === mode ? 'development' : 'production' ),
        },
        build: {
            outDir: '../build',
            // The minified build runs first (npm run build) and starts from a clean folder.
            emptyOutDir: minified,
            cssCodeSplit: false,
            sourcemap: 'development' === mode,
            minify: minified,
            // One bundle for one admin screen, as in CookieYes; no code splitting.
            chunkSizeWarningLimit: 2048,
            rollupOptions: {
                input: 'src/main.tsx',
                external: Object.keys( WORDPRESS_SCRIPTS ),
                output: {
                    format: 'iife',
                    globals: WORDPRESS_SCRIPTS,
                    entryFileNames: `settings-app${ suffix }.js`,
                    assetFileNames: `settings-app${ suffix }[extname]`,
                },
            },
        },
    };
} );
