import * as fs from "fs";
import { styleText } from "util";

export default function PackagesCheck() {
  try {
    if (!fs.existsSync("package.json")) {
      console.log(styleText("red", "package.jsonがありません。正規のリポジトリでgit pullを実行してください。"));
      process.exit();
    }

    // package.json取得
    const packages = JSON.parse(fs.readFileSync("package.json", "utf-8"));
    const dependencies = packages.dependencies;

    const packageNames: Array<string> = [];

    Object.keys(dependencies).forEach((packageName) => {
      let version: string;

      if (dependencies[packageName].charAt(0) === "^") {
        version = dependencies[packageName].replace('^', '');
      } else {
        version = dependencies[packageName]
      }

      dependencies[packageName] = version;
      packageNames.push(packageName);
    });

    // パッケージのバージョン取得
    const mismatchPackages: Array<string> = [];

    packageNames.forEach((packageName) => {
      const packagePath = `node_modules/${packageName}/package.json`;

      if (fs.existsSync(packagePath)) {
        const modulePackage = JSON.parse(fs.readFileSync(packagePath, "utf-8"));

        if (modulePackage.version !== dependencies[packageName]) {
          mismatchPackages.push(packageName);
        }
      } else {
        console.log(styleText("red", `パッケージ「${packageName}」が見つかりません。`));
        process.exit();
      }
    });

    if (mismatchPackages.length !== 0) {
      console.log(styleText("red", "以下のパッケージのバージョンが異なります:"));
      mismatchPackages.forEach((mismatch) => {
        console.log(styleText("red", mismatch));
        console.log(styleText("red", `  要求バージョン: ${dependencies[mismatch]}`));
      });
      process.exit();
    }
  } catch (err) {
    console.log("パッケージの存在確認でエラーが発生しました: ", err);
  }
}
