//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.

import { ConfigEnv, loadEnv, UserConfig } from 'vite';
import path from 'path';
import { ROUTER_BASE } from './src/model/router-utils';
import { wrapperViteEnv } from './build/utils';
import { loadVitePlugins } from './build/plugin';
import { configRollupOptions } from './build/script/rollupOption';

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const configs = wrapperViteEnv(env);
  const { VITE_SOURCE_MAP, VITE_USE_MOCK } = configs;

  return {
    base: ROUTER_BASE,
    publicDir: './src/static',
    plugins: loadVitePlugins(configs),
    server: {
      hmr: true,
      https: true,
      // mock 模式纯前端运行,不注册代理;代理 target 为空时请求转发会直接报错
      proxy: VITE_USE_MOCK
        ? undefined
        : {
            '/UI/Rest': {
              target: '',
              changeOrigin: true,
              secure: false
            },
            '/task': {
              target: '',
              changeOrigin: true,
              secure: false
            },
            '/download': {
              target: '',
              changeOrigin: true,
              secure: false
            },
            '/help': {
              target: '',
              changeOrigin: true,
              secure: false
            },
            '/extern': {
              target: '',
              changeOrigin: true,
              secure: false
            }
          }
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    build: {
      target: 'es2015',
      cssTarget: 'chrome64',
      sourcemap: VITE_SOURCE_MAP,
      rollupOptions: configRollupOptions()
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/assets/common/style/common/varible.scss" as *;',
          charset: false
        }
      }
    },
    test: {
      environment: 'happy-dom',
      reporter: ['default', 'verbose', 'junit'],
      outputFile: {
        junit: './tests/reports/js_test.xml'
      },
      coverage: {
        enabled: true,
        reporter: ['html'],
        reportsDirectory: './tests/reports'
      }
    }
  };
};