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 { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
import {
  COMMUNICATION_CHANNELS_CONNECT_CREDENTIAL_CHANNEL_COMMAND_ID
} from "../../../../../commands/connect-credential-channel.js";
import { validateRouteMutationGuard } from "../../../../../lib/route-mutation-guard.js";
const metadata = {
  path: "/communication_channels/channels/connect/credentials",
  POST: {
    requireAuth: true,
    requireFeatures: ["communication_channels.connect_user_channel"]
  }
};
const bodySchema = z.object({
  providerKey: z.string().min(1).max(64),
  displayName: z.string().min(1).max(255),
  credentials: z.record(z.string(), z.unknown()),
  pollIntervalSeconds: z.number().int().positive().max(86400).optional()
});
async function POST(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.sub || !auth?.tenantId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  let body;
  try {
    const json = await readJsonSafe(req, null);
    body = bodySchema.parse(json);
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Invalid request body" },
      { status: 422 }
    );
  }
  const container = await createRequestContainer();
  const guard = await validateRouteMutationGuard({
    container,
    req,
    auth,
    input: {
      resourceKind: "communication_channels.channel",
      resourceId: `new:${body.providerKey}`,
      operation: "create",
      mutationPayload: {
        providerKey: body.providerKey,
        displayName: body.displayName,
        pollIntervalSeconds: body.pollIntervalSeconds
      }
    }
  });
  if ("response" in guard) return guard.response;
  const commandBus = container.resolve("commandBus");
  const input = {
    providerKey: body.providerKey,
    displayName: body.displayName,
    credentials: body.credentials,
    pollIntervalSeconds: body.pollIntervalSeconds,
    userId: auth.sub,
    scope: {
      tenantId: auth.tenantId,
      organizationId: auth.orgId ?? null
    }
  };
  const { result } = await commandBus.execute(COMMUNICATION_CHANNELS_CONNECT_CREDENTIAL_CHANNEL_COMMAND_ID, {
    input,
    ctx: {
      container,
      auth,
      organizationScope: null,
      selectedOrganizationId: auth.orgId ?? null,
      organizationIds: auth.orgId ? [auth.orgId] : null
    }
  });
  if (result.status === "no_adapter") {
    return NextResponse.json({ error: result.reason }, { status: 404 });
  }
  if (result.status === "validation_failed") {
    return NextResponse.json({ error: "Credential validation failed", fieldErrors: result.errors }, { status: 422 });
  }
  if (result.status === "duplicate_mailbox") {
    return NextResponse.json(
      {
        error: `This mailbox is already connected via "${result.existingProviderKey}". Disconnect it there before connecting it again with a different provider.`,
        code: "mailbox_already_connected"
      },
      { status: 409 }
    );
  }
  await guard.afterSuccess();
  return NextResponse.json(
    {
      channelId: result.channelId,
      externalIdentifier: result.externalIdentifier
    },
    { status: 201 }
  );
}
const openApi = {
  tags: ["CommunicationChannels"],
  methods: {
    POST: {
      summary: "Connect a credential-based per-user channel (IMAP/SMTP)",
      tags: ["CommunicationChannels"],
      responses: [
        { status: 201, description: "Channel connected" },
        { status: 401, description: "Unauthorized" },
        { status: 404, description: "Unknown provider" },
        { status: 409, description: "Mailbox already connected via another provider" },
        { status: 422, description: "Invalid body or credential validation failed" }
      ]
    }
  }
};
var route_default = POST;
export {
  POST,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
