import type { ApiClient } from "@/shared/api/client.js";

export interface HealthMiddlewareOptions {
  apiClient: ApiClient;
  upstreamTimeoutMs?: number;
}

/** Express-style response with status/json helpers. */
interface HealthResponse {
  status(code: number): HealthResponse;
  json(body: unknown): void;
}

const STALE_THRESHOLD_MS = 60_000;
const DEFAULT_UPSTREAM_TIMEOUT_MS = 5_000;

/**
 * Factory that creates a health-check handler. Returns 200 if the last
 * successful upstream ping is within 60 s, 503 otherwise.
 *
 * This is an Express-style `(req, res, next)` handler — it does NOT
 * auto-register itself as Modern.js middleware. Registration happens
 * in a future integration step.
 */
export function healthMiddleware(options: HealthMiddlewareOptions) {
  const { apiClient, upstreamTimeoutMs = DEFAULT_UPSTREAM_TIMEOUT_MS } =
    options;

  let lastSuccessTs = 0;

  return async (
    _req: unknown,
    res: HealthResponse,
    _next: () => void,
  ): Promise<void> => {
    // Attempt to ping the upstream API
    try {
      await Promise.race([
        apiClient.get("/health"),
        new Promise<never>((_resolve, reject) =>
          setTimeout(
            () => reject(new Error("upstream_timeout")),
            upstreamTimeoutMs,
          ),
        ),
      ]);
      lastSuccessTs = Date.now();
    } catch {
      // ping failed — rely on cached lastSuccessTs
    }

    const age = Date.now() - lastSuccessTs;

    if (lastSuccessTs > 0 && age < STALE_THRESHOLD_MS) {
      res.status(200).json({ status: "ok" });
    } else {
      res
        .status(503)
        .json({ status: "degraded", reason: "upstream_unreachable" });
    }
  };
}
