// Backup routes — Task 7 of docs/superpowers/plans/2026-07-31-local-app.md.
// A pg_dump is a whole-database dump, not scoped to one company, so these
// routes are registered OUTSIDE /api/c/ — like registerCompanyRoutes, they
// need no X-Company-Id header and companyContextPlugin's preHandler simply
// doesn't apply to them (it only fires for /api/c/* URLs).

import type { FastifyInstance } from "fastify";
import {
  runBackup, lastBackupInfo, countBackups, defaultBackupDir, BACKUP_ALREADY_RUNNING_MESSAGE,
} from "./backup.js";

export function registerBackupRoutes(fastify: FastifyInstance): void {
  fastify.post("/api/backup", async (request, reply) => {
    try {
      const result = await runBackup({});
      return reply.send(result);
    } catch (err) {
      const message = (err as Error).message;
      if (message === BACKUP_ALREADY_RUNNING_MESSAGE) {
        // Not a failure — expected when a daily/manual backup is already
        // mid-flight (see backup.ts's inFlightBackup guard). 409, not 500:
        // nothing went wrong, the request just can't proceed right now.
        return reply.code(409).send({ error: message });
      }
      request.log.error({ err }, "manual backup failed");
      return reply.code(500).send({ error: message });
    }
  });

  fastify.get("/api/backup/status", async (request, reply) => {
    const dir = defaultBackupDir();
    try {
      const [last, count] = await Promise.all([lastBackupInfo(dir), countBackups(dir)]);
      return reply.send({
        dir,
        lastBackup: last
          ? { file: last.file, ageHours: (Date.now() - last.mtime.getTime()) / 3_600_000 }
          : null,
        count,
      });
    } catch (err) {
      request.log.error({ err }, "backup status check failed");
      return reply.code(500).send({ error: "Couldn't check the backup folder." });
    }
  });
}
