import { fileURLToPath } from 'node:url';

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

import ElementPlus from 'unplugin-element-plus/vite';

import { createBasePathRedirectPlugin } from './vite-base-path-redirect';

const resourceListChunkEntries = [
  './src/components/headerSearch/HeaderSearch.vue',
  './src/components/page/CardList.vue',
  './src/components/page/PageData.vue',
  './src/components/page/PageSide.vue',
].map((file) => fileURLToPath(new URL(file, import.meta.url)));

function isResourceListModule(id: string) {
  return resourceListChunkEntries.some(
    (entry) => id === entry || id.startsWith(`${entry}?`),
  );
}

export default defineConfig(async () => {
  return {
    application: {},
    vite: {
      build: {
        rollupOptions: {
          output: {
            manualChunks(id) {
              if (isResourceListModule(id)) {
                return 'resource-list';
              }
            },
            onlyExplicitManualChunks: true,
          },
        },
      },
      resolve: {
        alias: {
          // @vueuse/motion expects tslib default export during dev pre-bundling
          // and breaks when Vite resolves to ESM-only modules/index.js.
          tslib: 'tslib/tslib.js',
        },
      },
      plugins: [
        createBasePathRedirectPlugin(),
        ElementPlus({
          format: 'esm',
        }),
      ],
      server: {
        proxy: {
          '/flow/api': {
            changeOrigin: true,
            headers: {
              'X-Forwarded-Prefix': '/flow',
            },
            rewrite: (path) => path.replace(/^\/flow/, ''),
            target: 'http://127.0.0.1:8111',
            ws: true,
            xfwd: true,
          },
          '/flow/public-api': {
            changeOrigin: true,
            headers: {
              'X-Forwarded-Prefix': '/flow',
            },
            rewrite: (path) => path.replace(/^\/flow/, ''),
            target: 'http://127.0.0.1:8111',
            xfwd: true,
          },
          '/flow/userCenter': {
            changeOrigin: true,
            headers: {
              'X-Forwarded-Prefix': '/flow',
            },
            rewrite: (path) => path.replace(/^\/flow/, ''),
            target: 'http://127.0.0.1:8111',
            xfwd: true,
          },
        },
      },
    },
  };
});
