/**
 * Plugin to minimize and use ejs template syntax in index.html.
 * https://github.com/anncwb/vite-plugin-html
 */
import type { PluginOption } from 'vite';
import { createHtmlPlugin } from 'vite-plugin-html';
// import pkg from '../../../package.json';
// import { GLOB_CONFIG_FILE_NAME } from '../../constant';
import { simpleGit } from 'simple-git';
const git = simpleGit();

async function getLatestHash() {
  const gitLog = await git.log();
  /** 截取git hash值最后8位 */
  const lastStrNum = 8;
  return gitLog.latest?.hash.substring(-lastStrNum, lastStrNum);
}

export function configHtmlPlugin(env: ViteEnv, isBuild: boolean): Promise<PluginOption[]> {
  const { VITE_GLOB_APP_TITLE } = env;

  const path = './';

  // const getAppConfigSrc = () => {
  //   return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`;
  // };

  return new Promise((resolve) => {
    getLatestHash().then((hash) => {
      const htmlPlugin: PluginOption[] = createHtmlPlugin({
        minify: isBuild,
        inject: {
          // Inject data into ejs template
          data: {
            title: VITE_GLOB_APP_TITLE,
            hash,
          },
          // // Embed the generated app.config.js file
          // tags: isBuild
          //   ? [
          //       {
          //         tag: 'script',
          //         attrs: {
          //           src: getAppConfigSrc(),
          //         },
          //       },
          //     ]
          //   : [],
        },
      });
      resolve(htmlPlugin);
    });
  });
}
