import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CommunicationChannel } from "../../../../data/entities.js";
const metadata = {
  path: "/communication_channels/me/channels",
  GET: {
    requireAuth: true,
    requireFeatures: ["communication_channels.connect_user_channel"]
  }
};
async function GET(req) {
  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 channels = await findWithDecryption(
    em,
    CommunicationChannel,
    {
      tenantId: auth.tenantId,
      organizationId: auth.orgId ?? null,
      userId: auth.sub,
      deletedAt: null
    },
    { orderBy: { createdAt: "desc" } },
    { tenantId: auth.tenantId, organizationId: auth.orgId ?? null }
  );
  return NextResponse.json({
    items: channels.map(serialize),
    total: channels.length
  });
}
function serialize(channel) {
  const channelState = channel.channelState ?? null;
  const pushStatus = typeof channelState?.pushStatus === "string" ? channelState.pushStatus : null;
  const lastPushError = channelState?.lastPushError && typeof channelState.lastPushError === "object" ? {
    code: channelState.lastPushError.code ?? null,
    message: channelState.lastPushError.message ?? null,
    at: channelState.lastPushError.at ?? null
  } : null;
  return {
    id: channel.id,
    providerKey: channel.providerKey,
    channelType: channel.channelType,
    displayName: channel.displayName,
    externalIdentifier: channel.externalIdentifier ?? null,
    isPrimary: channel.isPrimary,
    isActive: channel.isActive,
    status: channel.status,
    lastError: channel.lastError ?? null,
    pollIntervalSeconds: channel.pollIntervalSeconds ?? null,
    lastPolledAt: channel.lastPolledAt?.toISOString?.() ?? null,
    pushStatus,
    lastPushError,
    createdAt: channel.createdAt?.toISOString?.() ?? null
  };
}
const openApi = {
  tags: ["CommunicationChannels"],
  methods: {
    GET: {
      summary: "List the current user's connected channels",
      tags: ["CommunicationChannels"],
      responses: [
        { status: 200, description: "List of user-owned channels" },
        { status: 401, description: "Unauthorized" }
      ]
    }
  }
};
var route_default = GET;
export {
  GET,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
