import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import postcssRemToResponsivePixel from 'postcss-rem-to-responsive-pixel'
import postcssWeappTailwindcssRename from 'weapp-tailwindcss-webpack-plugin/postcss'
import vwt from 'weapp-tailwindcss-webpack-plugin/vite'
import uniRouter from 'unplugin-uni-router/vite'

const isH5 = process.env.UNI_PLATFORM === 'h5'
const isApp = process.env.UNI_PLATFORM === 'app'
const weappTailwindcssDisabled = isH5 || isApp

const postcssPlugin = [autoprefixer(), tailwindcss()]
if (!weappTailwindcssDisabled) {
    postcssPlugin.push(
        postcssRemToResponsivePixel({
            rootValue: 32,
            propList: ['*'],
            transformUnit: 'rpx'
        })
    )
    postcssPlugin.push(postcssWeappTailwindcssRename())
}

const suppressUniRouterSourcemapWarning = (msg: string) =>
    msg.includes('plugin (unplugin-uni-router) was used to transform files') &&
    msg.includes("didn't generate a sourcemap")

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd(), '')

    return {
        plugins: [uni(), uniRouter(), weappTailwindcssDisabled ? undefined : vwt()],
        customLogger: {
            info(msg) { console.log(msg) },
            warn(msg) { if (suppressUniRouterSourcemapWarning(msg)) return; console.warn(msg) },
            error(msg) { console.error(msg) },
            warnOnce(msg) { if (suppressUniRouterSourcemapWarning(msg)) return; console.warn(msg) },
            infoOnce(msg) { console.log(msg) },
            clearScreen() { },
            hasWarned: false,
            hasErrorLogged: false,
        },
        build: {
            rollupOptions: {
                onwarn(warning, warn) {
                    if (
                        warning.message?.includes('plugin (unplugin-uni-router) was used to transform files') &&
                        warning.message?.includes("didn't generate a sourcemap")
                    ) {
                        return
                    }
                    warn(warning)
                }
            }
        },
        css: {
            postcss: {
                plugins: postcssPlugin
            }
        },
        server: {
            port: 5177,
            proxy: isH5 && env.VITE_APP_BASE_URL
                ? {
                    '/api': {
                        target: env.VITE_APP_BASE_URL,
                        changeOrigin: true,
                    },
                }
                : undefined,
        }
    }
})
