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, wrapperEnv, isDevFn } 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'],
        },
        build: {
            target: 'es2015',
            sourcemap: isDevFn(mode) ? true : false,
            rollupOptions: {
                output: {
                    inlineDynamicImports: false,
                },
            },
        },
        define: {
            __APP__: {
                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,
        },
    }
}
