import { defineConfig } from '@vben/vite-config';

import dayjs from 'dayjs';
import ElementPlus from 'unplugin-element-plus/vite';
import { loadEnv } from 'vite';
import mkcert from 'vite-plugin-mkcert';

import pkg from './package.json';

const __APP_INFO__ = {
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  pkg,
};

export default defineConfig(async ({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const isDev = env.VITE_NODE_ENV === 'development';
  return {
    application: {},
    define: {
      // 注入环境变量到客户端
      __APP_ENV__: JSON.stringify(env),
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    vite: {
      plugins: [
        isDev && mkcert(),
        ElementPlus({
          format: 'esm',
        }),
      ],
      server: {
        http2: true,
        https: true,
        port: isDev ? Number(env.VITE_PORT) : undefined,
        proxy: {
          '/api': {
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, ''),
            // mock代理目标地址
            target: 'http://localhost:5320/api',
            ws: true,
          },
        },
      },
    },
  };
});
