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 { CustomEntity } from "@open-mercato/core/modules/entities/data/entities";
const metadata = {
  GET: { requireAuth: true }
};
async function GET(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId || !auth.orgId && !auth.isSuperAdmin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const { resolve } = await createRequestContainer();
  const em = resolve("em");
  const cache = resolve("cache");
  const where = {
    isActive: true,
    showInSidebar: true
  };
  where.$and = [
    //    { $or: [ { organizationId: auth.orgId ?? undefined as any }, { organizationId: null } ] }, // the entities and custom fields are defined per tenant
    { $or: [{ tenantId: auth.tenantId ?? void 0 }, { tenantId: null }] }
  ];
  const cacheKey = `entities:sidebar:${auth.tenantId || "null"}`;
  try {
    if (cache) {
      const cached = await cache.get(cacheKey);
      if (cached && Array.isArray(cached.items)) return NextResponse.json(cached);
    }
  } catch {
  }
  const entities = await em.find(CustomEntity, where, { orderBy: { label: "asc" } });
  const items = entities.map((e) => ({
    entityId: e.entityId,
    label: e.label,
    href: `/backend/entities/user/${encodeURIComponent(e.entityId)}/records`
  }));
  const payload = { items };
  try {
    if (cache) await cache.set(cacheKey, payload, { tags: [`nav:entities:${auth.tenantId || "null"}`] });
  } catch {
  }
  return NextResponse.json(payload);
}
const sidebarEntitiesResponseSchema = z.object({
  items: z.array(
    z.object({
      entityId: z.string(),
      label: z.string(),
      href: z.string()
    })
  )
});
const openApi = {
  tag: "Entities",
  summary: "List sidebar entities",
  methods: {
    GET: {
      summary: "Get sidebar entities",
      description: "Returns custom entities flagged with `showInSidebar` for the current tenant/org scope.",
      responses: [
        {
          status: 200,
          description: "Sidebar entities for navigation",
          schema: sidebarEntitiesResponseSchema
        },
        {
          status: 401,
          description: "Missing authentication",
          schema: z.object({ error: z.string() })
        }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=sidebar-entities.js.map
