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 {
  queueImportHistory,
  queueImportHistorySchema
} from "../../../../../commands/queue-import-history.js";
import { validateRouteMutationGuard } from "../../../../../lib/route-mutation-guard.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("communication_channels").child({ component: "import-history" });
const metadata = {
  path: "/communication_channels/channels/[id]/import-history",
  POST: {
    requireAuth: true,
    requireFeatures: ["communication_channels.connect_user_channel"]
  }
};
const bodySchema = queueImportHistorySchema.omit({ channelId: true });
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 });
  }
  let rawBody;
  try {
    const text = await req.text();
    rawBody = text ? JSON.parse(text) : {};
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }
  const parsed = bodySchema.safeParse(rawBody);
  if (!parsed.success) {
    const first = parsed.error.issues[0];
    return NextResponse.json(
      {
        error: first?.message ?? "Invalid request",
        fieldErrors: first ? { [first.path.join(".")]: first.message } : void 0
      },
      { status: 400 }
    );
  }
  const container = await createRequestContainer();
  const em = container.resolve("em").fork();
  const organizationId = auth.orgId ?? null;
  if (!organizationId) {
    return NextResponse.json({ error: "No organization scope" }, { status: 400 });
  }
  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.channel.import_history"
    );
  } 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: parsed.data
    }
  });
  if ("response" in guard) return guard.response;
  try {
    const result = await queueImportHistory({
      container,
      scope: {
        tenantId: auth.tenantId,
        organizationId,
        userId: auth.sub
      },
      input: { channelId: id, ...parsed.data }
    });
    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("failed to enqueue for channel", { channelId: id, err });
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Failed to queue import-history" },
      { status: 500 }
    );
  }
}
const openApi = {
  tags: ["CommunicationChannels"],
  methods: {
    POST: {
      summary: "Queue a backlog import for a channel (Spec B \xA7 Phase B6)",
      tags: ["CommunicationChannels"],
      requestBody: {
        required: true,
        contentType: "application/json",
        schema: bodySchema
      },
      responses: [
        { status: 202, description: "Import job queued; returns { progressJobId }" },
        { status: 400, description: "Invalid channel id or unsupported provider" },
        { status: 401, description: "Unauthorized" },
        { status: 404, description: "Channel not found / not accessible" },
        { status: 409, description: "Channel is not connected (requires reauth / error)" },
        {
          status: 429,
          description: "Another import is already running for this channel"
        }
      ]
    }
  }
};
var route_default = POST;
export {
  POST,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
