import { getPluginsList } from "./build/plugins";
import { include, exclude } from "./build/optimize";
import { type UserConfigExport, type ConfigEnv, loadEnv } from "vite";
import {
  root,
  alias,
  wrapperEnv,
  pathResolve,
  __APP_INFO__
} from "./build/utils";

export default async ({ mode }: ConfigEnv): Promise<UserConfigExport> => {
  const { VITE_CDN, VITE_PORT, VITE_COMPRESSION, VITE_PUBLIC_PATH } =
    wrapperEnv(loadEnv(mode, root));
  
  // 统一的后端服务地址
  const API_BASE_URL = "http://localhost:7070/admin";
  
  // 需要代理的 API 路径列表
  const apiPaths = [
    "/login",
    "/user",
    "/role",
    "/permission",
    "/users",
    "/shops",
    "/devices",
    "/order",
    "/products",
    "/inventory",
    "/marketing",
    "/checkin",
    "/announcement",
    "/operation-log",
    "/sync",
    "/new-product-apply",
    "/dashboard",
    "/dict",
    "/timed-discount",
    "/layer-templates",
    "/distribution",
    "/refund",
    "/replenishers",
    "/menu",
    "/upload",
    "/replenishment-orders",
    "/erp-goods",
    "/erp-shops"
  ];
  
  // 动态生成代理配置
  const proxyConfig: Record<string, any> = {};
  apiPaths.forEach(path => {
    proxyConfig[path] = {
      target: API_BASE_URL,
      changeOrigin: true,
      rewrite: (p: string) => p.replace(new RegExp(`^${path}`), path),
      bypass: (req: any) => {
        if (req.headers?.accept?.includes('text/html')) {
          return '/index.html';
        }
      }
    };
  });
  
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias
    },
    server: {
      port: VITE_PORT,
      host: "0.0.0.0",
      proxy: proxyConfig,
      warmup: {
        clientFiles: ["./index.html", "./src/{views,components}/*"]
      }
    },
    plugins: await getPluginsList(VITE_CDN, VITE_COMPRESSION),
    optimizeDeps: {
      include,
      exclude
    },
    build: {
      target: "es2015",
      sourcemap: false,
      chunkSizeWarningLimit: 4000,
      rolldownOptions: {
        input: {
          index: pathResolve("./index.html", import.meta.url)
        },
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]"
        },
        checks: {
          pluginTimings: false,
          toleratedTransform: false
        }
      }
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    }
  };
};
