import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { batiaoPlugin } from '@batiao/batiao-sdk-vue-vite/onBuild'
import proxy from './src/proxy.cjs'
import fs from 'fs'

const copyPublicPlugin = () => {
  return {
    name: 'copy-src-public',
    closeBundle() {
      const srcDir = resolve(__dirname, 'src/public')
      const destDir = resolve(__dirname, 'dist/src/public')
      try {
        if (fs.existsSync(srcDir)) {
          fs.mkdirSync(destDir, { recursive: true })
          fs.cpSync(srcDir, destDir, { recursive: true })
          console.log('[copy-src-public] 成功将 src/public 复制到 dist/src/public')
        }
      } catch (err) {
        console.error('[copy-src-public] 复制失败:', err)
      }
    }
  }
}

export default defineConfig({
  plugins: [vue(), batiaoPlugin(), copyPublicPlugin()],
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler'
      }
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  build: {
    chunkSizeWarningLimit: 2000,
    rollupOptions: {
      onwarn(warning, warn) {
        if (warning.code === 'UNRESOLVED_IMPORT' || warning.code === 'UNUSED_EXTERNAL_IMPORT') return;
        warn(warning);
      }
    }
  },
  server: {
    //通过电脑ip访问设置
    host: '0.0.0.0',
    port: 3000,
    proxy
  }
})
