import { NextResponse } from "next/server";
import { z } from "zod";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getIntegration } from "@open-mercato/shared/modules/integrations/types";
import {
  resolveUserFeatures,
  runIntegrationMutationGuardAfterSuccess,
  runIntegrationMutationGuards
} from "../../guards.js";
const idParamsSchema = z.object({ id: z.string().min(1) });
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["integrations.manage"] }
};
const openApi = {
  tags: ["Integrations"],
  summary: "Run health check for an integration"
};
async function POST(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const rawParams = ctx.params && typeof ctx.params.then === "function" ? await ctx.params : ctx.params;
  const parsedParams = idParamsSchema.safeParse(rawParams);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid integration id" }, { status: 400 });
  }
  const integration = getIntegration(parsedParams.data.id);
  if (!integration) {
    return NextResponse.json({ error: "Integration not found" }, { status: 404 });
  }
  const container = await createRequestContainer();
  const guardResult = await runIntegrationMutationGuards(
    container,
    {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub ?? "",
      resourceKind: "integrations.integration",
      resourceId: integration.id,
      operation: "update",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: { integrationId: integration.id }
    },
    resolveUserFeatures(auth)
  );
  if (!guardResult.ok) {
    return NextResponse.json(guardResult.errorBody ?? { error: "Operation blocked by guard" }, { status: guardResult.errorStatus ?? 422 });
  }
  const healthService = container.resolve("integrationHealthService");
  const result = await healthService.runHealthCheck(
    integration.id,
    { organizationId: auth.orgId, tenantId: auth.tenantId }
  );
  await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {
    tenantId: auth.tenantId,
    organizationId: auth.orgId,
    userId: auth.sub ?? "",
    resourceKind: "integrations.integration",
    resourceId: integration.id,
    operation: "update",
    requestMethod: req.method,
    requestHeaders: req.headers
  });
  return NextResponse.json({
    status: result.status,
    message: result.message ?? null,
    details: result.details ?? null,
    latencyMs: result.latencyMs,
    checkedAt: result.checkedAt
  });
}
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
