import { NextResponse } from "next/server";
import { execSync } from "node:child_process";

/**
 * Answers one question: is the code on this server actually the code that is
 * running?
 *
 * Two separate facts, because they can disagree:
 *
 *   checkedOut - the commit sitting in the checkout right now, read live from
 *                git on every request.
 *   built      - the commit the running bundle was compiled from, inlined at
 *                build time (see BUILD_COMMIT in next.config.ts).
 *
 * A deploy pulls, then builds, then restarts PM2. If the build fails,
 * bin/deploy.sh restores the previous build and leaves PM2 alone - so the
 * checkout moves forward while the running app does not. That is the state
 * that looks like "I pushed but nothing changed", and it is exactly when
 * these two values differ.
 *
 * public/deploy-info.json cannot answer this on its own: the deploy script
 * writes it before building, so it always advertises the newly pulled commit
 * whether or not that commit ever made it into a bundle.
 */
export const dynamic = "force-dynamic";

export function GET() {
  const built = process.env.BUILD_COMMIT?.trim() || null;

  let checkedOut: string | null = null;
  try {
    checkedOut = execSync("git rev-parse HEAD", {
      cwd: process.cwd(),
      // Never let a git error reach the response body.
      stdio: ["ignore", "pipe", "ignore"],
    })
      .toString()
      .trim();
  } catch {
    checkedOut = null;
  }

  const inSync = built && checkedOut ? built === checkedOut : null;

  return NextResponse.json(
    {
      built,
      builtShort: built ? built.slice(0, 7) : null,
      checkedOut,
      checkedOutShort: checkedOut ? checkedOut.slice(0, 7) : null,
      inSync,
      status:
        inSync === null
          ? "unknown - could not read one of the two commits"
          : inSync
            ? "running the checked-out commit"
            : "STALE - checkout is ahead of the running build; the build or restart did not complete",
    },
    {
      headers: {
        // A cached answer here would defeat the entire point.
        "Cache-Control": "no-store, max-age=0",
      },
    },
  );
}
