import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { cancelSchema } from "../../data/validators.js";
import { paymentGatewaysTag } from "../openapi.js";
import {
  resolveUserFeatures,
  runPaymentGatewayMutationGuardAfterSuccess,
  runPaymentGatewayMutationGuards
} from "../guards.js";
const gatewayTransactionResourceKind = "payment_gateways.gateway_transaction";
const metadata = {
  path: "/payment_gateways/cancel",
  POST: { requireAuth: true, requireFeatures: ["payment_gateways.manage"] }
};
async function POST(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const payload = await readJsonSafe(req);
  const parsed = cancelSchema.safeParse(payload);
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid payload", details: parsed.error.flatten() }, { status: 422 });
  }
  const container = await createRequestContainer();
  const guardResult = await runPaymentGatewayMutationGuards(
    container,
    {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub ?? "",
      resourceKind: gatewayTransactionResourceKind,
      resourceId: parsed.data.transactionId,
      operation: "update",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: parsed.data
    },
    resolveUserFeatures(auth)
  );
  if (!guardResult.ok) {
    return NextResponse.json(
      guardResult.errorBody ?? { error: "Operation blocked by guard" },
      { status: guardResult.errorStatus ?? 422 }
    );
  }
  const service = container.resolve("paymentGatewayService");
  try {
    const result = await service.cancelPayment(
      parsed.data.transactionId,
      parsed.data.reason,
      { organizationId: auth.orgId, tenantId: auth.tenantId }
    );
    await runPaymentGatewayMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub ?? "",
      resourceKind: gatewayTransactionResourceKind,
      resourceId: parsed.data.transactionId,
      operation: "update",
      requestMethod: req.method,
      requestHeaders: req.headers
    });
    return NextResponse.json(result);
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    const message = err instanceof Error ? err.message : "Cancel failed";
    return NextResponse.json({ error: message }, { status: 502 });
  }
}
const openApi = {
  tags: [paymentGatewaysTag],
  summary: "Cancel/void an authorized payment",
  methods: {
    POST: {
      summary: "Cancel payment",
      tags: [paymentGatewaysTag],
      responses: [
        { status: 200, description: "Payment cancelled" },
        { status: 409, description: "Invalid payment status transition" },
        { status: 422, description: "Invalid payload" },
        { status: 502, description: "Gateway provider error" }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
