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 envMode = process.env.MODE || process.env.NODE_ENV || 'development'

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

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

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 sdkClientType = envConf[mode].sdkClientType || 'open'

const basename = '/sdream-fe'

const viteOutputObj = process.env.VITE_OUTPUT_OBJ || 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': sdkMock,
      'import.meta.env.VITE_SDK_API_BASE_URL': JSON.stringify(sdkApiBaseUrl),
      'import.meta.env.VITE_OUTPUT_OBJ': JSON.stringify(viteOutputObj),
      'import.meta.env.VITE_SDK_CLIENT_TYPE': JSON.stringify(sdkClientType),
    },
  },
  server: {
    proxy: {
      [apiUrl]: {
        target: proxyUrl,
        pathRewrite: { [`^${apiUrl}`]: '' },
        changeOrigin: true,
      },
    },
  },
})
