// /scripts/bumpVersion.js
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");

const envPaths = [
  path.join(__dirname, "../.env.development"),
  path.join(__dirname, "../.env.production"),
];
const pkgPath = path.join(__dirname, "../package.json");

// 🟢 Versionsnummer aus package.json holen
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
const [major, minor, patch] = pkg.version.split(".").map(Number);
const newVersion = `${major}.${minor}.${patch + 1}`;

// 🟢 package.json aktualisieren
pkg.version = newVersion;
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), "utf8");

// 🟢 .env Dateien aktualisieren
envPaths.forEach(envFile => {
  if (!fs.existsSync(envFile)) return;

  let content = fs.readFileSync(envFile, "utf8");
  const versionRegex = /^NEXT_PUBLIC_APP_VERSION=.*$/m;

  if (versionRegex.test(content)) {
    content = content.replace(versionRegex, `NEXT_PUBLIC_APP_VERSION=${newVersion}`);
  } else {
    content += `\nNEXT_PUBLIC_APP_VERSION=${newVersion}`;
  }

  fs.writeFileSync(envFile, content, "utf8");
});

// 🟢 package-lock.json aktualisieren
try {
  execSync("npm install --package-lock-only", { stdio: "inherit" });
} catch (error) {
  console.error("❌ Fehler beim Aktualisieren der package-lock.json:", error);
  process.exit(1);
}

console.log(`✅ Version erhöht auf ${newVersion}`);
