import config from "../config.js";
import { readFileSync, writeFileSync, existsSync } from "fs";

export default async function VersionCheck() {
  const packageJson = JSON.parse(readFileSync("package.json", "utf-8"));

  // 初期化
  if (!existsSync("logs/version.txt")) {
    writeFileSync(
      "logs/version.txt",
      packageJson.version,
      "utf-8",
    );
  }

  // 最終起動バージョン取得
  const oldVersion = readFileSync("logs/version.txt", "utf-8");

  if (oldVersion !== packageJson.version) {
    try {
      writeFileSync(
        "logs/version.txt",
        packageJson.version,
        "utf-8",
      );

      const releaseUrl = `${packageJson.repository.url}/releases/tag/${packageJson.tag}`;

      await fetch(`${config.uwuzu.host}/api/ueuse/create`, {
        method: "POST",
        body: JSON.stringify({
          token: config.uwuzu.apiToken,
          text: `
          ${packageJson.version}にBOTがアップデートされました！
          リリース内容：${releaseUrl}
          `,
        }),
        cache: "no-store",
      });
    } catch (err) {
      console.log("アップデート通知にエラーが発生しました: ", err);
    }
  }
}
