import { fileURLToPath, URL } from 'node:url';

import vue from '@vitejs/plugin-vue';
import { defineConfig, loadEnv } from 'vite';
// import electron from 'vite-plugin-electron'
// import vueDevTools from 'vite-plugin-vue-devtools'
import mkcert from "vite-plugin-mkcert";
import { viteMockServe } from 'vite-plugin-mock';
// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd())
  console.log('\x1b[36m%s\x1b[0m', '[VITE_APP_ENV]', env.VITE_APP_ENV)
  console.log('\x1b[33m%s\x1b[0m', '[VITE_APP_BASE_API]', env.VITE_APP_BASE_API)

  // 将环境变量转换为 process.env 格式
  const processEnv = {}
  Object.keys(env).forEach(key => {
    processEnv[key] = JSON.stringify(env[key])
  })

  return {
    plugins: [
      vue(),
      mkcert({
        source: 'coding',
        autoUpgrade: true,
        force: true,
      }),
      viteMockServe({
        mockPath: 'src/mocks',
        localEnabled: true,
        prodEnabled: false,
        supportTs: true,
        watchFiles: true,
        logger: true,
        injectFile: 'src/main.js',
        injectCode: `
          import { setupProdMockServer } from 'src/mocks/index.js';
          setupProdMockServer();
        `,

      }),
      // electron({
      //   entry: 'electron/main.js',
      // }),
      // vueDevTools(),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler'
        }
      }
    },
    server: {
      host: true,
      port: 31003,
      https: true,
      cors: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          secure: false,
          ws: true,
          configure: (proxy, options) => {

          }
        }
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'vendor': ['vue', 'vue-router', 'pinia']
          }
        }
      },
      chunkSizeWarningLimit: 1500,
      terserOptions: {
        compress: {
          // drop_console: true,
          drop_debugger: true
        }
      }
    },
    define: {
      'process.env': processEnv
    }
  }
})
