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 { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CommunicationChannel } from "../../../../../../data/entities.js";
import { ChannelAccessDeniedError, assertCanManageChannel } from "../../../../../../lib/access-control.js";
import { pushRegister } from "../../../../../../commands/push-register.js";
import { validateRouteMutationGuard } from "../../../../../../lib/route-mutation-guard.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("communication_channels").child({ component: "push-register" });
const metadata = {
  path: "/communication_channels/channels/[id]/push/register",
  POST: {
    requireAuth: true,
    requireFeatures: ["communication_channels.connect_user_channel"]
  }
};
async function POST(req, context) {
  const { id } = await context.params;
  if (!z.string().uuid().safeParse(id).success) {
    return NextResponse.json({ error: "Invalid channel id" }, { status: 400 });
  }
  const auth = await getAuthFromRequest(req);
  if (!auth?.sub || !auth?.tenantId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const organizationId = auth.orgId ?? null;
  if (!organizationId) {
    return NextResponse.json({ error: "No organization scope" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const em = container.resolve("em").fork();
  const channel = await findOneWithDecryption(
    em,
    CommunicationChannel,
    { id, tenantId: auth.tenantId, organizationId, deletedAt: null },
    void 0,
    { tenantId: auth.tenantId, organizationId }
  );
  if (!channel) {
    return NextResponse.json({ error: "Channel not found" }, { status: 404 });
  }
  let userFeatures = [];
  try {
    const rbac = container.resolve("rbacService");
    const acl = await rbac.loadAcl(auth.sub, {
      tenantId: auth.tenantId,
      organizationId
    });
    userFeatures = acl?.isSuperAdmin ? ["*"] : Array.isArray(acl?.features) ? acl.features : [];
  } catch {
    userFeatures = [];
  }
  try {
    assertCanManageChannel(
      { userId: channel.userId },
      auth.sub,
      userFeatures,
      "communication_channels.channel.push.manage"
    );
  } catch (err) {
    if (err instanceof ChannelAccessDeniedError) {
      return NextResponse.json({ error: "Channel not found" }, { status: 404 });
    }
    throw err;
  }
  const guard = await validateRouteMutationGuard({
    container,
    req,
    auth,
    input: {
      resourceKind: "communication_channels.channel",
      resourceId: id,
      operation: "custom",
      mutationPayload: { pushStatus: "register" }
    }
  });
  if ("response" in guard) return guard.response;
  try {
    const result = await pushRegister({
      container,
      scope: { tenantId: auth.tenantId, organizationId, userId: auth.sub },
      input: { channelId: id }
    });
    await guard.afterSuccess();
    return NextResponse.json({ ok: true, ...result }, { status: 202 });
  } catch (err) {
    const candidate = err;
    if (candidate && typeof candidate.status === "number") {
      return NextResponse.json(
        { error: candidate.message, fieldErrors: candidate.fieldErrors },
        { status: candidate.status }
      );
    }
    logger.error("push register failed for channel", { channelId: id, err });
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Failed to register push" },
      { status: 500 }
    );
  }
}
const openApi = {
  tags: ["CommunicationChannels"],
  methods: {
    POST: {
      summary: "Force-register push delivery for a channel (Spec C \xA7 Phase C5)",
      tags: ["CommunicationChannels"],
      responses: [
        { status: 202, description: "Push registration attempted; check result.pushStatus" },
        { status: 400, description: "Invalid id or unsupported provider" },
        { status: 401, description: "Unauthorized" },
        { status: 403, description: "Missing push.manage feature" },
        { status: 404, description: "Channel not found" },
        { status: 409, description: "Provider does not support push (IMAP)" },
        { status: 502, description: "Provider returned an error during registration" },
        { status: 503, description: "Webhook base URL or Pub/Sub topic not configured" }
      ]
    }
  }
};
var route_default = POST;
export {
  POST,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
