import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import legacy from '@vitejs/plugin-legacy';
import pages from 'vite-plugin-pages';

import ElementPlus from 'unplugin-element-plus/vite';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

const pathSrc = path.resolve(__dirname, 'src');

// https://vitejs.dev/config/
export default ({ mode }) => {
  const env = {
    // ...process.env,
    ...loadEnv(mode, process.cwd())
  };
  return defineConfig({
    base: env.VITE_BASE,
    build: {
      target: 'es2015',
      minify: 'terser',
      terserOptions: {
        compress: {
          // keep_infinity: true,
          // drop_console: VITE_DROP_CONSOLE,
        }
      },
      brotliSize: false,
      chunkSizeWarningLimit: 2000
    },
    optimizeDeps: {
      include: [],
      exclude: ['vue-demi']
    },
    esbuild: {},
    css: {
      preprocessorOptions: {
        scss: {
         additionalData: `@use "~/styles/element/index.scss" as *;`,
        },
        less: {
          javascriptEnabled: true
        }
      }
    },
    preview: {
      proxy: {
        '/uploads': {
          target: env.VITE_PROXY_UPLOADS,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/uploads/, '')
        },
        '/api': {
          target: env.VITE_PROXY_API,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      }
    },
    server: {
      proxy: {
        '/uploads': {
          target: env.VITE_PROXY_UPLOADS,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/uploads/, '')
        },
        '/api': {
          target: env.VITE_PROXY_API,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      }
    },
    resolve: {
      alias: {
        '~/': `${pathSrc}/`
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      ElementPlus({
        useSource: true
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      }),
      legacy(),
      pages({
        exclude: ['**/components/**']
      })
    ]
  });
};
