import { defineConfig } from 'vite'
import { resolve } from 'path'
import uni from '@dcloudio/vite-plugin-uni'

const uniPlugin = uni.default || uni

const vueCompatPlugin = () => {
  const virtualId = '\0virtual:vue-compat'
  const publicId = 'virtual:vue-compat'
  return {
    name: 'vue-compat-uni',
    resolveId(id) {
      if (id === publicId) return virtualId
      if (id === 'vue') return virtualId
      return null
    },
    load(id) {
      if (id !== virtualId) return null
      return [
        "import * as VueRuntime from 'vue/dist/vue.runtime.esm-bundler.js'",
        "export * from 'vue/dist/vue.runtime.esm-bundler.js'",
        'export default VueRuntime',
        'export const injectHook = () => {}',
        'export const isInSSRComponentSetup = () => false'
      ].join('\n')
    }
  }
}

export default defineConfig(({ command }) => {
  const isMpWeixin = process.env.UNI_PLATFORM === 'mp-weixin'
  const inputDir = process.env.UNI_INPUT_DIR || '.'
  const mpEntry = resolve(inputDir, 'main.js')
  const outDir = isMpWeixin
    ? (command === 'serve' ? 'unpackage/dist/dev/mp-weixin' : 'unpackage/dist/build/mp-weixin')
    : 'dist'
  return {
    envDir: __dirname,
    server: {
      watch: {
        usePolling: true,
        interval: 100
      },
      hmr: true
    },
    resolve: {
      alias: [
        { find: /^vue$/, replacement: 'virtual:vue-compat' }
      ]
    },
    build: {
      outDir,
      emptyOutDir: false,
      rollupOptions: isMpWeixin
        ? { input: mpEntry }
        : undefined
    },
    plugins: [vueCompatPlugin(), uniPlugin()]
  }
})
