import process from 'node:process'
import { loadEnv } from 'vite'
import type { ConfigEnv, UserConfig } from 'vite'

import dayjs from 'dayjs'
import pkg from './package.json'
import { createVitePlugins } from './build/vite'
import { getRootPath, isDevFn, wrapperEnv } from './build/utils'

// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv): UserConfig => {
    const root = process.cwd()
    const env = wrapperEnv(loadEnv(mode, root))

    return {
        resolve: {
            alias: [
                // /@xxxx => src/xxxx
                {
                    find: /\/?@\//,
                    replacement: `${getRootPath('./src')}/`,
                },
                // /#xxxx => types/xxxx
                {
                    find: /\/#\//,
                    replacement: `${getRootPath('./types')}/`,
                },
            ],
        },
        plugins: createVitePlugins(env),
        optimizeDeps: {
            include: ['lodash-es', '@vueuse/core'],
        },
        esbuild: {
            drop: isDevFn(mode) ? [] : ['console', 'debugger'],
        },
        build: {
            target: 'es2015',
            sourcemap: !!isDevFn(mode),
            rollupOptions: {
                output: {
                    inlineDynamicImports: false,
                },
            },
        },
        css: {
            preprocessorOptions: {
                scss: {
                    api: 'modern-compiler',
                    silenceDeprecations: ['legacy-js-api', 'color-functions', 'import'],
                },
            },
        },
        define: {
            __APP__: {
                appName: pkg.appName || pkg.description,
                name: pkg.name,
                version: pkg.version,
                description: pkg.description,
                author: pkg.author,
                lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            },
            'process.env': process.env,
        },
    }
}
