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 {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
const paramsSchema = z.object({ id: z.string().uuid() });
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["data_sync.run"] }
};
const openApi = {
  tags: ["DataSync"],
  summary: "Cancel a running sync"
};
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 parsed = paramsSchema.safeParse(rawParams);
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid run id" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const syncRunService = container.resolve("dataSyncRunService");
  const progressService = container.resolve("progressService");
  const integrationLogService = container.resolve("integrationLogService");
  const integrationStateService = container.resolve("integrationStateService");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const run = await syncRunService.getRun(parsed.data.id, scope);
  if (!run) {
    return NextResponse.json({ error: "Run not found" }, { status: 404 });
  }
  if (run.status !== "running" && run.status !== "pending") {
    return NextResponse.json({ error: "Only pending or running runs can be cancelled" }, { status: 409 });
  }
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: auth.tenantId,
    organizationId: scope.organizationId,
    userId: auth.sub,
    resourceKind: "data_sync.run",
    resourceId: run.id,
    operation: "custom",
    requestMethod: req.method,
    requestHeaders: req.headers,
    mutationPayload: { action: "cancel" }
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  const progressCtx = {
    tenantId: auth.tenantId,
    organizationId: auth.orgId,
    userId: auth.sub
  };
  if (run.progressJobId) {
    try {
      await progressService.markCancelled(run.progressJobId, progressCtx);
    } catch (error) {
      const job = await progressService.getJob(run.progressJobId, progressCtx);
      const cancelRequested = job && (job.status === "running" || job.status === "cancelled") ? await progressService.isCancellationRequested(run.progressJobId, progressCtx.tenantId, progressCtx.organizationId) : false;
      if (job?.status !== "cancelled" && !cancelRequested) {
        throw error;
      }
    }
  }
  await syncRunService.markStatus(run.id, "cancelled", scope);
  await integrationStateService.upsert(run.integrationId, {
    lastHealthStatus: "degraded",
    lastHealthCheckedAt: /* @__PURE__ */ new Date()
  }, scope);
  await integrationLogService.write({
    integrationId: run.integrationId,
    runId: run.id,
    level: "warn",
    message: "Sync run cancelled",
    payload: {
      operationalStatus: "cancelled",
      summary: "The sync run was cancelled before completion."
    }
  }, scope);
  if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
    await runCrudMutationGuardAfterSuccess(container, {
      tenantId: auth.tenantId,
      organizationId: scope.organizationId,
      userId: auth.sub,
      resourceKind: "data_sync.run",
      resourceId: run.id,
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      metadata: guardResult.metadata ?? null
    });
  }
  return NextResponse.json({ ok: true });
}
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=cancel.js.map
