import { forwardMessageSchema } from "../../../data/validators.js";
import { attachOperationMetadataHeader } from "../../../lib/operationMetadata.js";
import { canUseMessageEmailFeature, parseRequestBodySafe, resolveMessageContext } from "../../../lib/routeHelpers.js";
import { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from "../../guards.js";
import { forwardResponseSchema, forwardMessageSchema as forwardSchema } from "../../openapi.js";
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["messages.compose"] }
};
async function POST(req, { params }) {
  const { ctx, scope } = await resolveMessageContext(req);
  const commandBus = ctx.container.resolve("commandBus");
  const body = await parseRequestBodySafe(req);
  const input = forwardMessageSchema.parse(body);
  if (input.sendViaEmail && !await canUseMessageEmailFeature(ctx, scope)) {
    return Response.json({ error: "Missing feature: messages.email" }, { status: 403 });
  }
  const guardResult = await runMessageMutationGuards(
    ctx.container,
    {
      tenantId: scope.tenantId,
      organizationId: scope.organizationId,
      userId: scope.userId,
      resourceKind: "messages.message",
      resourceId: null,
      operation: "create",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: input
    },
    resolveUserFeatures(ctx.auth)
  );
  if (!guardResult.ok) {
    return Response.json(
      guardResult.errorBody ?? { error: "Operation blocked by guard" },
      { status: guardResult.errorStatus ?? 422 }
    );
  }
  let commandResult;
  try {
    commandResult = await commandBus.execute("messages.messages.forward", {
      input: {
        ...input,
        messageId: params.id,
        tenantId: scope.tenantId,
        organizationId: scope.organizationId,
        userId: scope.userId
      },
      ctx: {
        container: ctx.container,
        auth: ctx.auth ?? null,
        organizationScope: null,
        selectedOrganizationId: scope.organizationId,
        organizationIds: scope.organizationId ? [scope.organizationId] : null,
        request: req
      }
    });
  } catch (error) {
    if (error instanceof Error) {
      if (error.message === "Message not found") {
        return Response.json({ error: "Message not found" }, { status: 404 });
      }
      if (error.message === "Access denied") {
        return Response.json({ error: "Access denied" }, { status: 403 });
      }
      if (error.message === "Forward is not allowed for this message type") {
        return Response.json({ error: "Forward is not allowed for this message type" }, { status: 409 });
      }
      if (error.message === "Forward body exceeds maximum length") {
        return Response.json({ error: "Forward body exceeds maximum length" }, { status: 413 });
      }
    }
    throw error;
  }
  const newMessageId = commandResult.result.id;
  const response = Response.json({ id: newMessageId }, { status: 201 });
  attachOperationMetadataHeader(response, commandResult.logEntry, {
    resourceKind: "messages.message",
    resourceId: newMessageId
  });
  await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {
    tenantId: scope.tenantId,
    organizationId: scope.organizationId,
    userId: scope.userId,
    resourceKind: "messages.message",
    resourceId: newMessageId,
    operation: "create",
    requestMethod: req.method,
    requestHeaders: req.headers
  });
  return response;
}
const openApi = {
  tag: "Messages",
  methods: {
    POST: {
      summary: "Forward a message and optionally include attachments from the forwarded conversation slice",
      requestBody: { schema: forwardSchema },
      responses: [
        {
          status: 201,
          description: "Message forwarded",
          schema: forwardResponseSchema
        },
        { status: 403, description: "Access denied" },
        { status: 404, description: "Message not found" },
        { status: 409, description: "Forward not allowed for message type" },
        { status: 413, description: "Forward body exceeds maximum length" }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
