import { ResolvedConfig } from 'vite';
import { writeFile, mkdir, existsSync } from 'node:fs';
import { resolve } from 'node:path';

// 添加类型标注
const writeVersion = (versionFilePath: string, content: string): void => {
  // 写入文件
  writeFile(versionFilePath, content, (err: NodeJS.ErrnoException | null) => {
    if (err) throw err;
  });
};

export const configVersionPlugin = (options: { lastBuildTime: string }) => {
  let config: ResolvedConfig | null = null;

  return {
    name: 'version-update',

    configResolved(resolvedConfig: ResolvedConfig) {
      // 存储最终解析的配置
      config = resolvedConfig;
    },

    buildStart() {
      if (!config) {
        throw new Error('Config not resolved before build start.');
      }

      // 生成版本信息文件路径
      const file = resolve(config.publicDir, 'version.json');
      // 这里使用编译时间作为版本信息
      const content = JSON.stringify({ lastBuildTime: options.lastBuildTime });

      if (existsSync(config.publicDir)) {
        writeVersion(file, content);
      } else {
        mkdir(config.publicDir, { recursive: true }, (err: NodeJS.ErrnoException | null) => {
          if (err) throw err;
          writeVersion(file, content);
        });
      }
    },
  };
};
