import { defineConfig, loadEnv } from 'vite';
import {
  getRootPath,
  getSrcPath,
  viteDefine,
  setupVitePlugins,
  createViteProxy,
} from './build';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { getEnvConfig } from './.env-config.js';
// yarn add --dev @esbuild-plugins/node-globals-polyfill
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
// yarn add --dev @esbuild-plugins/node-modules-polyfill
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
// You don't need to add this to deps, it's included by @esbuild-plugins/node-modules-polyfill
import rollupNodePolyFill from 'rollup-plugin-node-polyfills';
import { resolve } from 'path';

const resolvePath = (...args) => {
  return resolve(__dirname, ...args);
};

export default defineConfig((configEnv) => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd());
  console.log('viteEnv:', viteEnv);

  const processEnvValues = {
    'process.env': Object.entries(viteEnv).reduce((prev, [key, val]) => {
      return {
        ...prev,
        [key]: val,
      };
    }, {}),
  };

  const rootPath = getRootPath();
  const srcPath = getSrcPath();

  const isOpenProxy = viteEnv.VITE_HTTP_PROXY === 'Y';
  const envConfig = getEnvConfig(viteEnv);

  return {
    base: viteEnv.VITE_BASE_URL,
    resolve: {
      alias: {
        '~': rootPath,
        '@': srcPath,
        'qs': 'rollup-plugin-node-polyfills/polyfills/qs',
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "${resolve(
            __dirname,
            'src/style/color.less'
          )}";`,
        },
      },
    },
    define: { ...viteDefine, ...processEnvValues },
    plugins: [
      ...setupVitePlugins(viteEnv),
      NodeModulesPolyfillPlugin(),
      NodeGlobalsPolyfillPlugin({
        process: true,
        buffer: true,
      }),
      createSvgIconsPlugin({
        iconDirs: [resolvePath('src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
        customDomId: '__svg__icons__dom__',
        svgoOptions: {
          full: true,
          plugins: [
            {
              name: 'removeAttrs',
              params: {
                attrs: ['class', 'data-name', 'fill', 'stroke'],
              },
            },
          ],
        },
      }),
    ],
    server: {
      host: '0.0.0.0',
      port: 8888,
      open: true,
      proxy: createViteProxy(isOpenProxy, envConfig),
    },
    preview: {
      port: 5050,
    },
    build: {
      reportCompressedSize: false,
      sourcemap: false,
      commonjsOptions: {
        ignoreTryCatch: false,
      },
      // target: ['chrome52'],
      // cssTarget: ['chrome52'],
      // rollupOptions: {
      //   plugins: [rollupNodePolyFill()],
      // },
    },
  };
});
