import { NextResponse } from "next/server";
import { z } from "zod";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getBackendRouteManifests } from "@open-mercato/shared/modules/registry";
import { resolveFeatureCheckContext } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { groupBackendRoutesByModule, resolveBackendChromePayload } from "../../lib/backendChrome.js";
const metadata = {
  GET: { requireAuth: true }
};
const sidebarNavItemSchema = z.lazy(
  () => z.object({
    id: z.string().optional(),
    href: z.string(),
    title: z.string(),
    defaultTitle: z.string().optional(),
    enabled: z.boolean().optional(),
    hidden: z.boolean().optional(),
    pageContext: z.enum(["main", "admin", "settings", "profile"]).optional(),
    iconName: z.string().optional(),
    iconMarkup: z.string().optional(),
    children: z.array(sidebarNavItemSchema).optional()
  })
);
const sectionItemSchema = z.lazy(
  () => z.object({
    id: z.string(),
    label: z.string(),
    labelKey: z.string().optional(),
    href: z.string(),
    order: z.number().optional(),
    iconName: z.string().optional(),
    iconMarkup: z.string().optional(),
    children: z.array(sectionItemSchema).optional()
  })
);
const sectionGroupSchema = z.object({
  id: z.string(),
  label: z.string(),
  labelKey: z.string().optional(),
  order: z.number().optional(),
  items: z.array(sectionItemSchema)
});
const adminNavResponseSchema = z.object({
  brand: z.object({
    name: z.string().optional(),
    logo: z.object({
      src: z.string(),
      alt: z.string().optional()
    }).nullable().optional()
  }).nullable().optional(),
  groups: z.array(
    z.object({
      id: z.string().optional(),
      name: z.string(),
      defaultName: z.string().optional(),
      items: z.array(sidebarNavItemSchema)
    })
  ),
  settingsSections: z.array(sectionGroupSchema),
  settingsPathPrefixes: z.array(z.string()),
  profileSections: z.array(sectionGroupSchema),
  profilePathPrefixes: z.array(z.string()),
  grantedFeatures: z.array(z.string()),
  roles: z.array(z.string())
});
const adminNavErrorSchema = z.object({
  error: z.string()
});
async function GET(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const { translate, locale } = await resolveTranslations();
  const container = await createRequestContainer();
  const cache = container.resolve("cache");
  let selectedOrganizationId;
  let selectedTenantId;
  try {
    const url = new URL(req.url);
    const orgParam = url.searchParams.get("orgId");
    const tenantParam = url.searchParams.get("tenantId");
    selectedOrganizationId = orgParam === null ? void 0 : orgParam || null;
    selectedTenantId = tenantParam === null ? void 0 : tenantParam || null;
  } catch {
    selectedOrganizationId = void 0;
    selectedTenantId = void 0;
  }
  let cacheScopeTenantId = auth.tenantId ?? null;
  let cacheScopeOrganizationId = auth.orgId ?? null;
  try {
    const { organizationId, scope } = await resolveFeatureCheckContext({
      container,
      auth,
      selectedId: selectedOrganizationId,
      tenantId: selectedTenantId,
      request: req
    });
    cacheScopeOrganizationId = organizationId;
    cacheScopeTenantId = scope.tenantId ?? auth.tenantId ?? null;
  } catch {
    cacheScopeOrganizationId = auth.orgId ?? null;
    cacheScopeTenantId = auth.tenantId ?? null;
    selectedOrganizationId = auth.orgId ?? null;
    selectedTenantId = auth.tenantId ?? null;
  }
  const cacheVersion = "v4";
  const cacheKey = `nav:sidebar:${cacheVersion}:${locale}:${auth.sub}:${cacheScopeTenantId || "null"}:${cacheScopeOrganizationId || "null"}`;
  try {
    if (cache?.get) {
      const cached = await cache.get(cacheKey);
      if (cached) return NextResponse.json(cached);
    }
  } catch {
  }
  const payload = await resolveBackendChromePayload({
    auth,
    locale,
    modules: groupBackendRoutesByModule(getBackendRouteManifests()),
    translate: (key, fallback) => key ? translate(key, fallback) : fallback,
    request: req,
    selectedOrganizationId,
    selectedTenantId
  });
  try {
    if (cache?.set) {
      const tags = [
        `rbac:user:${auth.sub}`,
        cacheScopeTenantId ? `rbac:tenant:${cacheScopeTenantId}` : void 0,
        `nav:entities:${cacheScopeTenantId || "null"}`,
        `nav:locale:${locale}`,
        `nav:sidebar:user:${auth.sub}`,
        cacheScopeTenantId ? `nav:sidebar:tenant:${cacheScopeTenantId}` : void 0,
        cacheScopeOrganizationId ? `nav:sidebar:organization:${cacheScopeOrganizationId}` : void 0,
        `nav:sidebar:scope:${auth.sub}:${cacheScopeTenantId || "null"}:${cacheScopeOrganizationId || "null"}:${locale}`,
        ...(Array.isArray(auth.roles) ? auth.roles : []).map((role) => `nav:sidebar:role:${role}`)
      ].filter(Boolean);
      await cache.set(cacheKey, payload, { tags });
    }
  } catch {
  }
  return NextResponse.json(payload);
}
const openApi = {
  tag: "Authentication & Accounts",
  summary: "Admin sidebar navigation",
  methods: {
    GET: {
      summary: "Resolve backend chrome bootstrap payload",
      description: "Returns the backend chrome payload available to the authenticated administrator after applying scope, RBAC, role defaults, and personal sidebar preferences.",
      responses: [
        { status: 200, description: "Backend chrome payload", schema: adminNavResponseSchema },
        { status: 401, description: "Unauthorized", schema: adminNavErrorSchema }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=nav.js.map
