import { resolve } from 'node:path'
import { merge } from 'lodash-es'
import { defineConfig, defineViteConfig, externalizeDepsPlugin } from 'electron-vite'
import type { ConfigEnv, UserConfig } from 'vite'
import { loadEnv } from 'vite'
import { wrapperEnv } from './build/utils'

export default defineConfig({
    main: defineViteConfig(({ command, mode }: ConfigEnv) => {
        // The boolean type read by loadEnv is a string. This function can be converted to boolean type
        const viteEnv = wrapperEnv(loadEnv(mode, process.cwd()), true)
        if (command === 'serve') {
            process.env.ELECTRON_RENDERER_URL = `http://localhost:${viteEnv.VITE_PORT}`
        }

        return {
            plugins: [externalizeDepsPlugin()],
            envPrefix: ['MAIN_VITE_', 'VITE_', 'ELECTRON_'],
            build: {
                lib: {
                    entry: resolve(__dirname, 'src-electron/main/index.ts'),
                },
            },
        }
    }),
    preload: {
        plugins: [externalizeDepsPlugin()],
        build: {
            lib: {
                entry: resolve(__dirname, 'src-electron/preload/index.ts'),
            },
        },
    },
    renderer: defineViteConfig(async (env): Promise<UserConfig> => {
        // 设置运行时环境，用于减少一些不必要的构建处理
        process.env.RUNTIME = 'electron'

        const defaultConfig = (await import('./vite.config')).default(env)
        const config: UserConfig = {
            envPrefix: 'VITE_',
            build: {
                target: 'chrome80',
                rollupOptions: {
                    input: {
                        index: resolve(__dirname, 'index.html'),
                    },

                    // 排除 electron + node 相关的依赖
                    external: ['node:*', 'path', 'fs', 'process', 'electron', 'electron-store'],
                },
            },
        }

        return merge(defaultConfig, config)
    }),
})
