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_DELETE_CHANNEL_COMMAND_ID
} from "../../../../commands/delete-channel.js";
import { validateRouteMutationGuard } from "../../../../lib/route-mutation-guard.js";
const metadata = {
  path: "/communication_channels/channels/[id]",
  DELETE: {
    // Owner self-service: a user may disconnect their OWN personal mailbox
    // (gated by `connect_user_channel`). Deleting a shared/tenant-wide channel
    // still requires `manage` — enforced per channel type by
    // `assertCanManageChannel` in the handler.
    requireAuth: true,
    requireFeatures: ["communication_channels.connect_user_channel"]
  }
};
async function DELETE(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;
  }
  const guard = await validateRouteMutationGuard({
    container,
    req,
    auth,
    input: {
      resourceKind: "communication_channels.channel",
      resourceId: id,
      operation: "delete"
    }
  });
  if ("response" in guard) return guard.response;
  const commandBus = container.resolve("commandBus");
  const input = {
    channelId: id,
    userId: auth.sub,
    scope: { tenantId: auth.tenantId, organizationId }
  };
  const { result } = await commandBus.execute(
    COMMUNICATION_CHANNELS_DELETE_CHANNEL_COMMAND_ID,
    {
      input,
      ctx: {
        container,
        auth,
        organizationScope: null,
        selectedOrganizationId: organizationId,
        organizationIds: organizationId ? [organizationId] : null
      }
    }
  );
  if (result.status !== "deleted") {
    return NextResponse.json({ error: "Channel not found" }, { status: 404 });
  }
  await guard.afterSuccess();
  return new NextResponse(null, { status: 204 });
}
const openApi = {
  tags: ["CommunicationChannels"],
  methods: {
    DELETE: {
      summary: "Delete (soft-delete) a communication channel",
      tags: ["CommunicationChannels"],
      responses: [
        { status: 204, description: "Channel deleted" },
        { status: 400, description: "Invalid channel id" },
        { status: 401, description: "Unauthorized" },
        { status: 404, description: "Channel not found or not owned by current user" }
      ]
    }
  }
};
var route_default = DELETE;
export {
  DELETE,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
