import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { Organization } from "@open-mercato/core/modules/directory/data/entities";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dictionaries").child({ component: "context" });
function resolveDictionaryActorId(auth) {
  if (auth && typeof auth.sub === "string" && auth.sub.trim().length > 0) return auth.sub;
  if (auth && typeof auth.userId === "string" && auth.userId.trim().length > 0) return auth.userId;
  if (auth && typeof auth.keyId === "string" && auth.keyId.trim().length > 0) return auth.keyId;
  return "system";
}
async function resolveDictionariesRouteContext(req) {
  const container = await createRequestContainer();
  const auth = await getAuthFromRequest(req);
  const { translate } = await resolveTranslations();
  if (!auth || !auth.tenantId) {
    throw new CrudHttpError(401, { error: translate("dictionaries.errors.unauthorized", "Unauthorized") });
  }
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const em = container.resolve("em");
  const tenantId = scope?.tenantId ?? auth.tenantId;
  const organizationId = scope?.selectedId ?? auth.orgId ?? null;
  const normalizeId = (value) => {
    if (typeof value !== "string") return null;
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : null;
  };
  const candidateIds = /* @__PURE__ */ new Set();
  const pushCandidate = (value) => {
    const normalized = normalizeId(value);
    if (normalized) candidateIds.add(normalized);
  };
  pushCandidate(organizationId);
  if (Array.isArray(scope?.filterIds)) {
    for (const id of scope.filterIds) pushCandidate(id);
  }
  if (Array.isArray(scope?.allowedIds)) {
    for (const id of scope.allowedIds) pushCandidate(id);
  }
  pushCandidate(auth.orgId ?? null);
  const readableOrganizationIds = /* @__PURE__ */ new Set();
  try {
    const shouldLoadAll = candidateIds.size === 0;
    const organizations = await em.find(
      Organization,
      {
        tenant: tenantId,
        deletedAt: null,
        ...shouldLoadAll ? {} : { id: { $in: Array.from(candidateIds) } }
      },
      { fields: ["id", "ancestorIds"] }
    );
    for (const organization of organizations) {
      const id = normalizeId(organization.id);
      if (id) readableOrganizationIds.add(id);
      if (Array.isArray(organization.ancestorIds)) {
        for (const ancestorId of organization.ancestorIds) {
          const normalized = normalizeId(ancestorId);
          if (normalized) readableOrganizationIds.add(normalized);
        }
      }
    }
    if (!shouldLoadAll && readableOrganizationIds.size === 0) {
      for (const id of candidateIds) readableOrganizationIds.add(id);
    }
  } catch (err) {
    logger.warn("Failed to resolve readable organizations", { err });
    for (const id of candidateIds) readableOrganizationIds.add(id);
  }
  const ctx = {
    container,
    auth,
    organizationScope: scope,
    selectedOrganizationId: organizationId,
    organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),
    request: req
  };
  return {
    container,
    ctx,
    auth,
    em,
    organizationId,
    tenantId,
    readableOrganizationIds: Array.from(readableOrganizationIds),
    translate
  };
}
export {
  resolveDictionariesRouteContext,
  resolveDictionaryActorId
};
//# sourceMappingURL=context.js.map
