import {
  getIntegration,
  getBundle
} from "@open-mercato/shared/modules/integrations/types";
const HEALTH_CHECK_TIMEOUT_MS = 1e4;
function getEffectiveHealthCheckConfig(integrationId) {
  const definition = getIntegration(integrationId);
  if (!definition) return void 0;
  return definition.healthCheck ?? (definition.bundleId ? getBundle(definition.bundleId)?.healthCheck : void 0);
}
function isCredentialsEmpty(credentials) {
  if (credentials == null) return true;
  return Object.keys(credentials).length === 0;
}
function normalizeProbeResult(raw) {
  if (raw.status === "healthy" || raw.status === "degraded" || raw.status === "unhealthy") {
    return raw;
  }
  return { status: "unhealthy", message: raw.message ?? "Invalid health status", details: raw.details };
}
function timeoutPromise(ms) {
  return new Promise((_, reject) => {
    setTimeout(() => {
      reject(new Error("Health check timed out"));
    }, ms);
  });
}
function deriveIntegrationHealthStatus(input) {
  if (!input.hasHealthCheck || !input.hasCredentials) {
    return "unconfigured";
  }
  if (input.lastHealthStatus === "healthy" || input.lastHealthStatus === "degraded" || input.lastHealthStatus === "unhealthy") {
    return input.lastHealthStatus;
  }
  return "unconfigured";
}
function createHealthService(container, stateService, logService) {
  return {
    async runHealthCheck(integrationId, scope) {
      const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
      const healthConfig = getEffectiveHealthCheckConfig(integrationId);
      if (!healthConfig?.service) {
        return {
          status: "unconfigured",
          message: "No health check configured",
          latencyMs: null,
          checkedAt
        };
      }
      const credentialsService = container.resolve("integrationCredentialsService");
      const credentials = await credentialsService.resolve(integrationId, scope);
      if (isCredentialsEmpty(credentials)) {
        return {
          status: "unconfigured",
          message: "No credentials configured",
          latencyMs: null,
          checkedAt
        };
      }
      const startedAt = Date.now();
      let result;
      try {
        const checker = container.resolve(healthConfig.service);
        const raw = await Promise.race([
          checker.check(credentials, scope),
          timeoutPromise(HEALTH_CHECK_TIMEOUT_MS)
        ]);
        result = normalizeProbeResult(raw);
      } catch (error) {
        const message = error instanceof Error ? error.message : "Health check failed";
        result = { status: "unhealthy", message };
      }
      const latencyMs = Date.now() - startedAt;
      await stateService.upsert(
        integrationId,
        {
          lastHealthStatus: result.status,
          lastHealthCheckedAt: /* @__PURE__ */ new Date(),
          lastHealthLatencyMs: latencyMs
        },
        scope
      );
      const logger = logService.scoped(integrationId, scope);
      if (result.status === "healthy") {
        await logger.info("Health check passed", { status: result.status, ...result.details });
      } else {
        await logger.warn(`Health check: ${result.status}`, {
          status: result.status,
          message: result.message,
          ...result.details
        });
      }
      return {
        status: result.status,
        message: result.message,
        details: result.details,
        latencyMs,
        checkedAt: (/* @__PURE__ */ new Date()).toISOString()
      };
    }
  };
}
export {
  HEALTH_CHECK_TIMEOUT_MS,
  createHealthService,
  deriveIntegrationHealthStatus,
  getEffectiveHealthCheckConfig
};
//# sourceMappingURL=health-service.js.map
