import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import tailwindcss from '@tailwindcss/vite';

const isDev = process.env.NODE_ENV === 'development';
const isKV = process.env.VITE_USE_KV === 'true'; // use kevisual service as backend
const unamiPlugin = {
  name: 'html-transform',
  transformIndexHtml(html: string) {
    return html.replace(
      '</head>',
      `<script defer src="https://umami.xiongxiao.me/script.js" data-website-id="79e7aa98-9e6e-4eef-bc8b-9cbd0ecb11c3"></script></head>`,
    );
  },
};
const plugins = [];
if (!isDev) {
  plugins.push(unamiPlugin);
}
plugins.push(tailwindcss());
let proxy = {};
if (isKV) {
  proxy = {
    '/api': {
      target: 'https://kevisual.xiongxiao.me',
      changeOrigin: true,
      rewrite: (path: any) => path.replace(/^\/api/, '/api'),
    },
    '/api/router': {
      target: 'wss://kevisual.xiongxiao.me',
      changeOrigin: true,
      ws: true,
      rewriteWsOrigin: true,
      rewrite: (path: any) => path.replace(/^\/api/, '/api'),
    },
    '/resources': {
      target: 'https://kevisual.xiongxiao.me',
      changeOrigin: true,
      rewrite: (path: any) => path.replace(/^\/resources/, '/resources'),
    },
  };
}
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), ...plugins],

  css: {
    postcss: {},
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  define: {
    DEV_SERVER: JSON.stringify(process.env.NODE_ENV === 'development'),
  },
  base: isDev ? '/' : '/root/center/',
  server: {
    port: 6020,
    host: '0.0.0.0',
    proxy: {
      '/system/lib': {
        target: 'https://kevisual.xiongxiao.me',
        changeOrigin: true,
      },
      '/api': {
        target: 'http://localhost:4005',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/api'),
      },
      '/api/router': {
        target: 'ws://localhost:4005',
        changeOrigin: true,
        ws: true,
        rewriteWsOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/api'),
      },
      '/resources': {
        target: 'https://kevisual.xiongxiao.me',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/resources/, '/resources'),
      },
      ...proxy,
    },
  },
});
