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 { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from "../../../../../lib/queue.js";
import { validateRouteMutationGuard } from "../../../../../lib/route-mutation-guard.js";
const metadata = {
  path: "/communication_channels/channels/[id]/poll-now",
  POST: {
    // Owner self-service: a user may sync their OWN mailbox (gated by
    // `connect_user_channel`). Polling a shared/tenant-wide channel still
    // requires `manage` — enforced per channel type by `assertCanManageChannel`.
    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 container = await createRequestContainer();
  const em = container.resolve("em").fork();
  const organizationId = auth.orgId ?? null;
  const dscope = { tenantId: auth.tenantId, organizationId };
  const channel = await findOneWithDecryption(
    em,
    CommunicationChannel,
    {
      id,
      tenantId: auth.tenantId,
      organizationId,
      deletedAt: null
    },
    void 0,
    dscope
  );
  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.manage"
    );
  } catch (err) {
    if (err instanceof ChannelAccessDeniedError) {
      return NextResponse.json({ error: "Channel not found" }, { status: 404 });
    }
    throw err;
  }
  if (!channel.isActive) {
    return NextResponse.json({ error: "Channel is disabled" }, { status: 409 });
  }
  if (channel.status === "requires_reauth") {
    return NextResponse.json(
      { error: "Channel needs reauthentication \u2014 reconnect from /backend/profile/communication-channels" },
      { status: 409 }
    );
  }
  if (channel.status === "disconnected") {
    return NextResponse.json(
      { error: "Channel is disconnected \u2014 reconnect to resume polling" },
      { status: 409 }
    );
  }
  const guard = await validateRouteMutationGuard({
    container,
    req,
    auth,
    input: {
      resourceKind: "communication_channels.channel",
      resourceId: channel.id,
      operation: "custom",
      mutationPayload: { action: "poll-now" }
    }
  });
  if ("response" in guard) return guard.response;
  const queue = getCommunicationChannelsQueue(COMMUNICATION_CHANNELS_QUEUES.poll);
  const payload = {
    channelId: channel.id,
    scope: {
      tenantId: auth.tenantId,
      organizationId: organizationId ?? null
    },
    attempt: 1
  };
  await queue.enqueue(payload);
  await guard.afterSuccess();
  return NextResponse.json(
    {
      ok: true,
      channelId: channel.id,
      queued: true,
      message: "Poll queued \u2014 new messages will appear after the worker runs."
    },
    { status: 202 }
  );
}
const openApi = {
  tags: ["CommunicationChannels"],
  methods: {
    POST: {
      summary: "Manually trigger a poll cycle for a channel (demo / operator override)",
      tags: ["CommunicationChannels"],
      responses: [
        { status: 202, description: "Poll job enqueued" },
        { status: 400, description: "Invalid channel id" },
        { status: 401, description: "Unauthorized" },
        { status: 404, description: "Channel not found" },
        { status: 409, description: "Channel disabled or not connected" }
      ]
    }
  }
};
var route_default = POST;
export {
  POST,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
