/**
 * 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';
import dayjs from 'dayjs';
const git = simpleGit();

async function getLatestHash() {
  const gitLog = await git.log();

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

async function getBuildInfo() {
  const { current } = await git.branchLocal();
  const hash = await getLatestHash();
  return { currentBranch: current, hash };
}

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

  return new Promise((resolve) => {
    getBuildInfo().then(({ currentBranch, hash }) => {
      const htmlPlugin: PluginOption[] = createHtmlPlugin({
        minify: isBuild,
        inject: {
          // Inject data into ejs template
          data: {
            title: VITE_GLOB_APP_TITLE,
            hash,
            injectScript: `
            <script type="text/javascript">
  console.log("%cbuild branch, ${currentBranch}","background:#1777FF; padding: 3px 6px; border-radius: 4px" )
  console.log("%cbuild version: ${hash}", "background:#1777FF; padding: 3px 6px; border-radius: 4px");
  console.log("build time, ${dayjs().format('YYYY-MM-DD HH:mm:ss')}", )
  </script>`,
          },

          // // Embed the generated app.config.js file
          // tags: isBuild
          //   ? [
          //       {
          //         tag: 'script',
          //         attrs: {
          //           src: getAppConfigSrc(),
          //         },
          //       },
          //     ]
          //   : [],
        },
      });
      resolve(htmlPlugin);
    });
  });
}
