import { forbidden } from "@open-mercato/shared/lib/crud/errors";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("auth").child({ component: "tenant-access" });
const SUPER_ADMIN_SYMBOL = /* @__PURE__ */ Symbol.for("auth.tenantGuard.isSuperAdmin");
function normalizeTenantId(value) {
  if (value === void 0) return void 0;
  if (value === null) return null;
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : null;
  }
  return null;
}
async function resolveIsSuperAdmin(ctx) {
  const cacheStore = ctx;
  const cached = cacheStore[SUPER_ADMIN_SYMBOL];
  if (typeof cached === "boolean") return cached;
  const auth = ctx.auth;
  if (!auth?.sub) {
    cacheStore[SUPER_ADMIN_SYMBOL] = false;
    return false;
  }
  if (auth.isSuperAdmin === true) {
    cacheStore[SUPER_ADMIN_SYMBOL] = true;
    return true;
  }
  try {
    const rbac = ctx.container.resolve("rbacService");
    const acl = await rbac.loadAcl(auth.sub, {
      tenantId: auth.tenantId ?? null,
      organizationId: auth.orgId ?? null
    });
    const value = !!acl?.isSuperAdmin;
    cacheStore[SUPER_ADMIN_SYMBOL] = value;
    return value;
  } catch (error) {
    logger.error("Failed to resolve rbac", { err: error });
    cacheStore[SUPER_ADMIN_SYMBOL] = false;
    return false;
  }
}
async function enforceTenantSelection(ctx, requested) {
  const normalized = normalizeTenantId(requested);
  const actorTenant = normalizeTenantId(ctx.auth?.tenantId ?? null) ?? null;
  const isSuperAdmin = await resolveIsSuperAdmin(ctx);
  if (isSuperAdmin) {
    if (normalized === void 0) return actorTenant;
    return normalized ?? null;
  }
  if (!actorTenant) {
    if (normalized && normalized !== null) {
      throw forbidden("Not authorized to target this tenant.");
    }
    return actorTenant;
  }
  if (normalized === void 0) return actorTenant;
  if (normalized === actorTenant) return actorTenant;
  throw forbidden("Not authorized to target this tenant.");
}
export {
  enforceTenantSelection,
  normalizeTenantId,
  resolveIsSuperAdmin
};
//# sourceMappingURL=tenantAccess.js.map
