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

const DEV_CONSOLE_PREFIX = '/console';
const DEV_API_INTERNAL_PREFIX = '/__dev_api_internal__';
const DEV_API_PROD_PREFIX = '/__dev_api_prod__';
const DEV_INTERNAL_CONSOLE_TARGET = 'http://127.0.0.1:2700';
const DEV_INTERNAL_GOLANG_TARGET = 'http://127.0.0.1:2900';
const DEV_PROD_GOLANG_TARGET = 'https://jvapi.haiyihy.com';
const DEV_PROD_TARGET = 'https://yumi-admin.haiyihy.com';

function createPrefixRegExp(prefix: string) {
  return new RegExp(`^${prefix.replaceAll('/', '\\/')}`);
}

export default defineConfig(async () => {
  return {
    application: {},
    vite: {
      server: {
        proxy: {
          [`${DEV_API_INTERNAL_PREFIX}/go`]: {
            changeOrigin: true,
            rewrite: (path) =>
              path.replace(createPrefixRegExp(`${DEV_API_INTERNAL_PREFIX}/go`), ''),
            target: DEV_INTERNAL_GOLANG_TARGET,
            ws: true,
          },
          [DEV_API_INTERNAL_PREFIX]: {
            changeOrigin: true,
            rewrite: (path) =>
              path.replace(createPrefixRegExp(DEV_API_INTERNAL_PREFIX), DEV_CONSOLE_PREFIX),
            target: DEV_INTERNAL_CONSOLE_TARGET,
            ws: true,
          },
          [`${DEV_API_PROD_PREFIX}/go`]: {
            changeOrigin: true,
            rewrite: (path) =>
              path.replace(createPrefixRegExp(DEV_API_PROD_PREFIX), ''),
            target: DEV_PROD_GOLANG_TARGET,
            ws: true,
          },
          [DEV_API_PROD_PREFIX]: {
            changeOrigin: true,
            rewrite: (path) =>
              path.replace(createPrefixRegExp(DEV_API_PROD_PREFIX), DEV_CONSOLE_PREFIX),
            target: DEV_PROD_TARGET,
            ws: true,
          },
          '/console/go': {
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/console\/go/, ''),
            target: 'http://127.0.0.1:2900',
            ws: true,
          },
          '/console': {
            changeOrigin: true,
            target: 'http://127.0.0.1:2700',
            ws: true,
          },
        },
      },
    },
  };
});
