import type { HealthRegistry } from "@wrnexus/core";

export interface HealthHandlerOptions {
  exposeDetails?: boolean;
  cacheControl?: string;
}

export function createLivenessHandler(options: HealthHandlerOptions = {}) {
  return async (request: Request): Promise<Response> => {
    if (request.method !== "GET" && request.method !== "HEAD") {
      return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD" } });
    }
    return Response.json(
      { status: "up" },
      { status: 200, headers: { "cache-control": options.cacheControl ?? "no-store" } },
    );
  };
}

export function createReadinessHandler(
  registry: HealthRegistry,
  options: HealthHandlerOptions = {},
) {
  return async (request: Request): Promise<Response> => {
    if (request.method !== "GET" && request.method !== "HEAD") {
      return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD" } });
    }
    const result = await registry.check();
    const body = options.exposeDetails ? result : { status: result.status };
    return Response.json(body, {
      status: result.status === "down" ? 503 : 200,
      headers: { "cache-control": options.cacheControl ?? "no-store" },
    });
  };
}
