import { fileURLToPath, URL } from 'node:url'
import { cpSync, existsSync, rmSync } from 'node:fs'
import { resolve } from 'node:path'
import basicSsl from '@vitejs/plugin-basic-ssl'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

const buildDomain = 'https://hddp.guocai365.org.cn'

function copyImageAssets() {
  return {
    name: 'copy-image-assets',
    closeBundle() {
      const source = resolve(__dirname, 'src/assets/images')
      const target = resolve(__dirname, 'dist/assets/images')

      if (!existsSync(source)) {
        return
      }

      rmSync(target, { recursive: true, force: true })
      cpSync(source, target, { recursive: true })
    },
  }
}

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const useLocalAssets = env.VITE_ASSET_BUILD_LOCAL === 'true'

  return {
    base: command === 'build' ? '/h5/' : '/',
    define: {
      __APP_DOMAIN__: JSON.stringify(command === 'build' ? buildDomain : ''),
      __DEBUG__: JSON.stringify(command === 'serve'),
    },
    plugins: [
      vue(),
      vueDevTools(),
      basicSsl(),
      ...(useLocalAssets || !env.VITE_ASSET_BASE_URL ? [copyImageAssets()] : []),
    ],
    server: {
      host: true,
      proxy: {
        '/socket.io': {
          target: 'http://localhost:8082',
          changeOrigin: true,
          ws: true,
        },
        '/manager': {
          target: 'http://localhost:8082',
          changeOrigin: true,
        },
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
  }
})
