// Version + update-status routes — Task 1 of
// docs/superpowers/plans/2026-08-01-launch.md. Neither route is scoped to a
// company (the product version and the update feed are whole-app facts, not
// per-tenant data), so — like registerBackupRoutes — these are registered
// OUTSIDE /api/c/: no X-Company-Id header required, and
// companyContextPlugin's preHandler doesn't apply (it only fires for
// /api/c/* URLs).

import type { FastifyInstance } from "fastify";
import { getVersion } from "./version.js";
import { checkForUpdate, getUpdateStatus } from "./updates.js";

export function registerUpdateRoutes(fastify: FastifyInstance): void {
  fastify.get("/api/version", async () => ({ version: getVersion() }));

  // The cached result of the last check (server-start / daily / a previous
  // "Check now") — synchronous, never triggers a network call itself.
  fastify.get("/api/update-status", async () => getUpdateStatus());

  // Settings' "Check now" button — forces a fresh check regardless of the
  // 24h staleness threshold maybeDailyUpdateCheck() applies.
  fastify.post("/api/update-status/check", async (request, reply) => {
    try {
      const result = await checkForUpdate();
      return reply.send(result);
    } catch (err) {
      // checkForUpdate() itself never throws (every feed failure resolves
      // to a cached "unreachable" result) — this is a last-resort net
      // against something unexpected escaping it anyway, same posture as
      // every other route in this app.
      request.log.error({ err }, "forced update check failed");
      return reply.code(500).send({ error: "Couldn't check for updates." });
    }
  });
}
