import { defineConfig, type UserConfigExport } from '@tarojs/cli'
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin'
import { UnifiedWebpackPluginV5 } from 'weapp-tailwindcss/webpack'
import devConfig from './dev'
import prodConfig from './prod'
import path from 'path'
import { getEnvConfig } from './env.js'

// https://taro-docs.jd.com/docs/next/config
export default defineConfig<'webpack5'>(async (merge, { mode }) => {
  const baseConfig: UserConfigExport<'webpack5'> = {
    // 项目配置
    projectName: 'xinlong-taro',
    date: '2026-5-10',
    designWidth: 750,
    deviceRatio: {
      640: 2.34 / 2,
      750: 1,
      828: 1.81 / 2
    },
    sourceRoot: 'src',
    outputRoot: 'dist',
    plugins: [
      '@tarojs/plugin-platform-weapp',
      '@tarojs/plugin-platform-h5'
    ],

    // 编译配置
    defineConstants: {
      API_BASE_URL: JSON.stringify(getEnvConfig().API_BASE_URL),
      SERVER_API_URL: JSON.stringify(getEnvConfig().SERVER_API_URL),
      APP_NAME: JSON.stringify(getEnvConfig().APP_NAME),
      DEBUG: JSON.stringify(getEnvConfig().DEBUG),
    },
    copy: {
      patterns: [],
      options: {}
    },
    framework: 'react',
    compiler: {
      type: 'webpack5',
      prebundle: {
        enable: false
      }
    },
    // 开启持久化缓存 - 有效提升二次编译速度
    cache: {
      enable: false,
      type: 'filesystem',
      cacheDirectory: path.resolve(__dirname, '../.webpack-cache'),
      buildDependencies: {
        config: [__filename]
      }
    },

    // 小程序配置
    mini: {
      postcss: {
        pxtransform: {
          enable: true,
          config: {}
        },
        url: {
          enable: true,
          config: {
            limit: 1024
          }
        },
        cssModules: {
          enable: false,
          config: {
            namingPattern: 'module',
            generateScopedName: '[name]__[local]___[hash:base64:5]'
          }
        }
      },
      webpackChain(chain) {
        chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
        // weapp-tailwindcss: 自动处理 TailwindCSS 与 WXSS 的兼容性
        chain.merge({
          plugin: {
            'weapp-tailwindcss': {
              plugin: UnifiedWebpackPluginV5,
              args: [{
                appType: 'taro',
                rem2rpx: true,
              }]
            }
          }
        })
      }
    },

    // H5 配置
    h5: {
      publicPath: '/',
      staticDirectory: 'static',
      postcss: {
        autoprefixer: {
          enable: true
        },
        cssModules: {
          enable: false,
          config: {
            namingPattern: 'module',
            generateScopedName: '[name]__[local]___[hash:base64:5]'
          }
        }
      },
      webpackChain(chain) {
        chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
      }
    },
  }

  if (mode === 'development') {
    return merge({}, baseConfig, devConfig)
  }
  return merge({}, baseConfig, prodConfig)
})
