import { defineConfig, loadEnv } from '@rsbuild/core'
import { pluginVue } from '@rsbuild/plugin-vue'
import { pluginSass } from '@rsbuild/plugin-sass'
import AutoImport from 'unplugin-auto-import/rspack'
import Components from 'unplugin-vue-components/rspack'
import { VantResolver } from '@vant/auto-import-resolver'
import postcssPluginPxToViewport from 'postcss-px-to-viewport-8-plugin'
import path from 'path'
import { fileURLToPath } from 'url'
import { dirname } from 'path'

const __filename = fileURLToPath(import.meta.url) // 获取当前文件绝对路径
const __dirname = dirname(__filename) // 获取当前目录路径
const { publicVars } = loadEnv({ prefixes: ['APP_'] })

export default defineConfig(() => {
  return {
    plugins: [
      pluginVue(),
      pluginSass({
        sassLoaderOptions: {
          additionalData: `@use '@/assets/style/variables.scss' as *;`
        }
      })
    ],
    source: {
      define: publicVars,
      entry: {
        index: './src/main.js'
      },
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    },
    server: {
      host: '0.0.0.0',
      open: true,
      proxy: {
        [process.env.APP_BASE_API]: {
          target: process.env.APP_BASE_SERVER_URL,
          changeOrigin: true
        }
      }
    },
    tools: {
      postcss: {
        plugins: [
          postcssPluginPxToViewport({
            unitToConvert: 'px',
            viewportWidth: 375,
            unitPrecision: 6,
            viewportUnit: 'vw',
            fontViewportUnit: 'vw',
            propList: ['*'],
            selectorBlackList: ['van-'],
            minPixelValue: 1,
            mediaQuery: false,
            replace: true,
            exclude: [/node_modules/],
            include: [],
            landscape: false
          })
        ]
      },
      htmlPlugin: {
        template: './index.html'
      },
      rspack: {
        plugins: [
          AutoImport({
            resolvers: [VantResolver()]
          }),
          Components({
            resolvers: [VantResolver()]
          })
        ]
      }
    },
    output: {
      cleanDistPath: true,
      legalComments: 'none',
      overrideBrowserslist: ['iOS >= 9', 'Android >= 4.4', 'last 2 versions', '> 0.2%', 'not dead']
    },
    performance: {
      removeConsole: true
    }
  }
})
