/**
 * Routes de santé et statut de l'API
 * /health, /version, /maintenance
 */
import type { FastifyInstance } from "fastify";
import type { RouteContext } from "./types.js";
import { pingDb } from "../db.js";

export const registerHealthRoutes = async (
  app: FastifyInstance,
  ctx: RouteContext,
): Promise<void> => {
  const { db, config, packageVersion } = ctx;

  app.get("/health", async (_req, reply) => {
    try {
      await pingDb();
      return {
        name: "rollerlogic-api",
        env: config.appEnv,
        status: "ok",
        version: packageVersion,
      };
    } catch (error) {
      reply.code(503);
      return {
        name: "rollerlogic-api",
        env: config.appEnv,
        status: "degraded",
        error: "DB",
        version: packageVersion,
      };
    }
  });

  app.get("/version", async () => {
    return {
      name: "rollerlogic-api",
      version: packageVersion,
      env: config.appEnv,
      buildDate: new Date().toISOString().split("T")[0],
    };
  });

  app.get("/maintenance", async () => {
    try {
      const [rows] = await db.execute(
        "SELECT config_key, config_value FROM app_config WHERE config_key IN ('maintenance_mode', 'maintenance_message', 'maintenance_end', 'launch_date')",
      );
      let maintenanceMode = false;
      let message = "Mise à jour en cours. Veuillez patienter...";
      let maintenanceEnd: string | null = null;
      let launchDate: string | null = null;
      if (Array.isArray(rows)) {
        for (const row of rows) {
          const item = row as { config_key?: string; config_value?: string };
          const val = (item.config_value ?? "").trim();
          if (item.config_key === "maintenance_mode") {
            maintenanceMode = val === "1" || val.toLowerCase() === "true";
          }
          if (item.config_key === "maintenance_message" && val) {
            message = val;
          }
          if (item.config_key === "maintenance_end" && val) {
            maintenanceEnd = val;
          }
          if (item.config_key === "launch_date" && val && val !== "unset") {
            launchDate = val;
          }
        }
      }

      // Auto-désactiver la maintenance si maintenanceEnd est passé
      if (maintenanceMode && maintenanceEnd) {
        const endDate = new Date(maintenanceEnd);
        if (!isNaN(endDate.getTime()) && endDate.getTime() <= Date.now()) {
          // La maintenance est terminée, on la désactive automatiquement
          await db.execute(
            "UPDATE app_config SET config_value = '0' WHERE config_key = 'maintenance_mode'",
          );
          maintenanceMode = false;
          maintenanceEnd = null;
        }
      }

      return {
        maintenance: maintenanceMode,
        message: maintenanceMode ? message : null,
        maintenanceEnd: maintenanceMode ? maintenanceEnd : null,
        launchDate,
      };
    } catch {
      return {
        maintenance: false,
        message: null,
        maintenanceEnd: null,
        launchDate: null,
      };
    }
  });
};
