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

const isDev = process.env.NODE_ENV === 'development';
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: any[] = [basicSsl()];
if (!isDev) {
  plugins.push(unamiPlugin);
}

plugins.push(tailwindcss());
const devBackend = 'https://kevisual.silkyai.cn';
const meBackend = 'https://kevisual.xiongxiao.me';
// const backend = isDev ? devBackend : meBackend;
const backendWss =  devBackend.replace(/^https:/, 'wss:');
const backend = devBackend;
let proxy = {};
if (true) {
  proxy = {
    '/api': {
      target: backend,
      changeOrigin: true,
      ws: true,
      rewrite: (path: any) => path.replace(/^\/api/, '/api'),
    },
    '/api/router': {
      target: backendWss,
      changeOrigin: true,
      ws: true,
      rewriteWsOrigin: true,
      rewrite: (path: any) => path.replace(/^\/api/, '/api'),
    },
    '/user/login': {
      target: backend,
      changeOrigin: true,
      cookieDomainRewrite: 'localhost',
      rewrite: (path: any) => path.replace(/^\/user/, '/user'),
    },
  };
}
// 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: 'https://localhost:4005',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/api'),
      },
      '/api/router': {
        target: 'wss://localhost:4005',
        changeOrigin: true,
        ws: true,
        rewriteWsOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/api'),
      },
      ...proxy,
    },
  },
});
