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 { createSessionSchema } 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/sessions",
  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 = createSessionSchema.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: null,
      operation: "create",
      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 { transaction, session } = await service.createPaymentSession({
      providerKey: parsed.data.providerKey,
      paymentId: crypto.randomUUID(),
      orderId: parsed.data.orderId,
      amount: parsed.data.amount,
      currencyCode: parsed.data.currencyCode,
      captureMethod: parsed.data.captureMethod,
      description: parsed.data.description,
      successUrl: parsed.data.successUrl,
      cancelUrl: parsed.data.cancelUrl,
      metadata: parsed.data.metadata,
      presentation: parsed.data.presentation,
      organizationId: auth.orgId,
      tenantId: auth.tenantId
    });
    const redirectUrl = session.redirectUrl ?? (session.clientSession?.type === "redirect" ? session.clientSession.redirectUrl : null);
    await runPaymentGatewayMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub ?? "",
      resourceKind: gatewayTransactionResourceKind,
      resourceId: transaction.id,
      operation: "create",
      requestMethod: req.method,
      requestHeaders: req.headers
    });
    return NextResponse.json({
      transactionId: transaction.id,
      sessionId: session.sessionId,
      providerKey: transaction.providerKey,
      clientSecret: session.clientSecret,
      redirectUrl,
      providerData: session.providerData ?? null,
      clientSession: session.clientSession ?? null,
      status: session.status,
      paymentId: transaction.paymentId
    }, { status: 201 });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Failed to create payment session";
    const status = message.includes("No gateway adapter") ? 422 : 502;
    return NextResponse.json({ error: message }, { status });
  }
}
const openApi = {
  tags: [paymentGatewaysTag],
  summary: "Create a payment session via a gateway provider",
  methods: {
    POST: {
      summary: "Create payment session",
      tags: [paymentGatewaysTag],
      responses: [
        { status: 201, description: "Payment session created" },
        { status: 422, description: "Invalid payload or unknown provider" },
        { status: 502, description: "Gateway provider error" }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
