#!/usr/bin/env node
/**
 * Stamp one version across every package.json in the workspace.
 *
 * The git tag is what actually drives the image tags (docker/metadata-action in
 * .gitea/workflows/build.yml reads the tag, not any package.json). This script
 * exists so the checked-in manifests stop lying: they all sat at 0.1.0 while
 * real releases went out as v1.x, which makes a checkout impossible to place
 * against a running container.
 *
 * Usage:
 *   node scripts/set-version.mjs 1.2.0
 *   pnpm version:set 1.2.0
 *
 * Then, as one release commit:
 *   git commit -am "chore(release): v1.2.0"
 *   git tag v1.2.0 && git push origin master v1.2.0
 *
 * Note the tag carries the leading `v` but the deploy workflow's `tag` input
 * does NOT — metadata-action's {{version}} strips it, so the published image is
 * `1.2.0`. Dispatch `1.2.0`, tag `v1.2.0`.
 */
import { readFileSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..");

const MANIFESTS = [
  "package.json",
  "apps/api/package.json",
  "apps/web/package.json",
  "packages/database/package.json",
];

const version = process.argv[2];
if (!version) {
  console.error("usage: node scripts/set-version.mjs <x.y.z>");
  process.exit(1);
}
// Plain semver only — a leading `v` here would end up in the image tag and in
// every manifest, which is not what any consumer expects.
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) {
  console.error(`invalid version: ${version} (expected x.y.z, no leading "v")`);
  process.exit(1);
}

for (const rel of MANIFESTS) {
  const file = join(REPO, rel);
  const raw = readFileSync(file, "utf8");
  const pkg = JSON.parse(raw);
  const previous = pkg.version;
  pkg.version = version;
  // Match the 2-space + trailing-newline shape the files already have so the
  // release commit is a one-line diff per manifest.
  writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
  console.log(`${rel}: ${previous} -> ${version}`);
}

console.log(`\nnext: git commit -am "chore(release): v${version}" && git tag v${version}`);
