import { defineConfig, loadEnv } from '@rsbuild/core'
import { pluginReact } from '@rsbuild/plugin-react'
import { pluginLess } from '@rsbuild/plugin-less'
import { pluginSvgr } from '@rsbuild/plugin-svgr'
import type { EnvConfKey } from './src/config/env'
import { envConf } from './src/config/env'

const mode = process.env.MODE as EnvConfKey || 'dev'

const { parsed: env } = loadEnv({ mode, cwd: process.cwd() })

const apiUrl = envConf[mode].apiUrl || ''
const proxyUrl = envConf[mode].proxyUrl || ''
const sdkCode = envConf[mode].sdkCode || ''
const sdkChannel = envConf[mode].sdkChannel || ''
const sdkMock = envConf[mode].sdkMock || false
const sdkApiBaseUrl = envConf[mode].sdkApiBaseUrl || ''

const basename = '/sdream-fe'

const viteOutputObj = env.VITE_OUTPUT_OBJ || 'open'

export default defineConfig({
  plugins: [
    pluginReact(),
    pluginLess(),
    pluginSvgr(),
  ],
  dev: {
    assetPrefix: basename,
  },
  html: {
    title: '晓得. - 晓得解惑，让沟通更智能。',
    favicon: './src/assets/logo.png',
  },
  output: {
    target: 'web',
    assetPrefix: basename,
    distPath: {
      root: basename.slice(1),
      image: 'assets',
      svg: 'assets',
      font: 'assets',
      media: 'assets',
    },
    copy: [
      {
        from: './src/sdk/',
        to: './sdk/',
      },
    ],
  },
  source: {
    define: {
      'import.meta.env.MODE': JSON.stringify(mode),
      'import.meta.env.VITE_SDK_CODE': JSON.stringify(sdkCode),
      'import.meta.env.VITE_SDK_CHANNEL': JSON.stringify(sdkChannel),
      'import.meta.env.VITE_SDK_MOCK': JSON.stringify(sdkMock),
      'import.meta.env.VITE_SDK_API_BASE_URL': JSON.stringify(sdkApiBaseUrl),
      'import.meta.env.VITE_OUTPUT_OBJ': JSON.stringify(viteOutputObj),
    },
  },
  server: {
    proxy: {
      [apiUrl]: {
        target: proxyUrl,
        pathRewrite: { [`^${apiUrl}`]: '' },
        changeOrigin: true,
      },
    },
  },
})
