import { fileURLToPath, URL } from 'node:url';

import path from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { createHtmlPlugin } from 'vite-plugin-html';

import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

const IS_PRODUCTION = process.env.NODE_ENV === 'production';
// 当前场景
const SCENE = process.env.VITE_APP_SCENE;

if (SCENE != null) {
  console.log('当前场景:', SCENE);
}

// https://vite.dev/config/
export default defineConfig(() => {
  return {
    base: './',
    plugins: [
      createHtmlPlugin({
        inject: {
          data: {
            title: process.env.TITLE,
          },
        },
      }),
      vue(),
      vueJsx(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src/index', import.meta.url)),
        '@hotspot': fileURLToPath(new URL('./src/hotspot', import.meta.url)),
      },
      extensions: SCENE
        ? [
            `.${SCENE}.mjs`,
            `.${SCENE}.js`,
            `.${SCENE}.ts`,
            `.${SCENE}.jsx`,
            `.${SCENE}.tsx`,
            `.${SCENE}.json`,
            `.${SCENE}.vue`,
            '.mjs',
            '.js',
            '.ts',
            '.jsx',
            '.tsx',
            '.json',
            '.vue',
          ]
        : ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    server: {
      port: Number(process.env.PORT) || 80,
      host: '0.0.0.0',
      strictPort: true,
      cors: true,
    },
    build: {
      outDir: IS_PRODUCTION && SCENE ? `build/${SCENE}` : 'build',
      assetsDir: 'assets',
      sourcemap: process.env.SOURCE_MAP === 'true',
      rollupOptions: {
        input: {
          index: path.resolve(__dirname, 'index.html'),
          hotspot: path.resolve(__dirname, 'hotspot.html'),
        },
        output: {
          manualChunks: {
            vendors: ['vue', 'element-plus', 'swiper'],
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
        },
      },
    },
  };
});
