import legacy from '@vitejs/plugin-legacy';
import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
import removeConsole from 'vite-plugin-remove-console';
import topLevelAwait from 'vite-plugin-top-level-await';
import wasm from 'vite-plugin-wasm';

import { viteBuildInfo } from './build/buildInfo';
import { configCompressPlugin } from './build/compress';
import svgConvert from './build/svgConvert';
import { root, alias, wrapperEnv } from './build/utils';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
    const env = wrapperEnv(loadEnv(mode, root));
    const isProd = mode === 'production';

    return {
        base: env.VITE_BUILD_PUBLIC_PATH,
        plugins: [
            react(),
            wasm(),
            topLevelAwait(),
            legacy({
                targets: [
                    'chrome >= 87',
                    'safari >= 13',
                    'firefox >= 78',
                    'edge >= 88',
                    'not IE 11',
                ],
            }),
            isProd &&
                removeConsole({
                    includes: ['log', 'warn'],
                    external: ['error'],
                }),
            svgConvert(),
            viteBuildInfo(),
            configCompressPlugin(env.VITE_BUILD_COMPRESSION!),
        ].filter(Boolean),
        resolve: { alias },
        optimizeDeps: {
            exclude: ['brotli-wasm'],
        },
        css: {
            preprocessorOptions: {
                less: {
                    javascriptEnabled: true,
                },
                scss: {
                    additionalData: `@use "@/styles/variables" as *;`,
                },
            },
        },
        server: {
            port: env.VITE_DEV_PORT,
            host: '0.0.0.0',
            open: true,
            proxy: {
                '/dev/api/v1': {
                    target: env.VITE_DEV_PROXY_TARGET_API_BASE_URL,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/dev\/api\/v1/, ''),
                    secure: false,
                    configure: (proxy) => {
                        proxy.on('error', (err) => {
                            console.log('proxy error', err);
                        });
                        proxy.on('proxyReq', (_, req) => {
                            console.log(
                                'Sending Request to the Target:',
                                req.method,
                                req.url,
                                env.VITE_DEV_PROXY_TARGET_API_BASE_URL
                            );
                        });
                        proxy.on('proxyRes', (proxyRes, req) => {
                            console.log(
                                'Received Response from the Target:',
                                proxyRes.statusCode,
                                req.url
                            );
                        });
                    },
                },
            },
            warmup: {
                clientFiles: ['./index.html', './src/{pages,components}/*'],
            },
        },
        build: {
            outDir: 'dist',
            sourcemap: !isProd,
            // 为了处理 brotli-wasm 的引用问题，target 已改为使用 plugin-legacy 的 targets 控制
            // target: ['es2015', 'chrome87', 'safari13', 'firefox78', 'edge88'],
            // 与 plugin-legacy targets 对齐，使 CSS 压缩/转换兼容同一批浏览器（plugin-legacy 不处理 CSS）
            cssTarget: ['chrome87', 'safari13', 'firefox78', 'edge88'],
            rollupOptions: {
                output: {
                    // 产物文件名：入口/代码块用 [name]-[hash:8].js，静态资源用 [name]-[hash:8][extname]
                    entryFileNames: 'assets/[name]-[hash].js',
                    chunkFileNames: 'assets/[name]-[hash].js',
                    assetFileNames: 'assets/[name]-[hash][extname]',
                    manualChunks: {
                        'react-vendor': ['react', 'react-dom', 'react-router-dom'],
                        'antd-vendor': ['antd', '@ant-design/icons'],
                        'utils-vendor': ['lodash-es', 'ramda'],
                        'i18n-vendor': [
                            'i18next',
                            'react-i18next',
                            'i18next-browser-languagedetector',
                        ],
                    },
                },
            },
            chunkSizeWarningLimit: 1500,
        },
    };
});
