import { defineConfig, loadEnv } from 'vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import vue from '@vitejs/plugin-vue'
import ViteComponents from 'unplugin-vue-components/vite'
import DefineOptions from 'unplugin-vue-define-options/vite'
import { createServer as createLangServer } from './scripts/lang'

import { resolve } from 'path'

// https://vitejs.dev/config/
export default async ({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const langProt = 9091
  const proxy = {
    '/dev': {
      target: `http://localhost:${langProt}`,
      changeOrigin: true,
      rewrite: path => path.replace(/^\/dev/, '/dev')
    },
    '/api': {
      target: 'https://test-jp.4dkankan.com/',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/api/, '')
    },
    '/local': {
      target: 'http://192.168.0.152:8111',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/local/, '')
    }
  }
  const input: { [key in string]: string } = {}

  if (process.argv.includes('lang')) {
    await createLangServer(langProt)
    input.lang = resolve(__dirname, 'lang.html')
  } else {
    input.main = resolve(__dirname, 'index.html')
  }

  console.log(input)
  return defineConfig({
    build: {
      rollupOptions: {
        input
      }
    },
    base: './',
    plugins: [
      vue(),
      DefineOptions(),
      ViteComponents({
        resolvers: [
          AntDesignVueResolver({ resolveIcons: true, importStyle: 'less' })
        ],
        dts: 'src/components.d.ts'
      })
    ],
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          modifyVars: {
            'primary-color': '#0076F6',
            'link-color': '#0076F6',
            'border-radius-base': '2px'
          }
        }
      }
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: resolve(__dirname, './src')
        }
      ]
    },
    server: {
      host: '0.0.0.0',
      port: 5176,
      open: true,
      proxy: proxy
    }
  })
}
