import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("planner").child({ component: "access" });
function buildForbiddenError(translate) {
  return new CrudHttpError(403, {
    error: translate("planner.availability.errors.unauthorized", "Unauthorized")
  });
}
function buildStaffModuleNotLoadedError() {
  return new CrudHttpError(403, { error: "staff_module_not_loaded" });
}
async function resolveAvailabilityWriteAccess(ctx) {
  const tenantId = ctx.auth?.tenantId ?? null;
  const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null;
  const resolver = ctx.container.resolve(
    "availabilityAccessResolver",
    { allowUnregistered: true }
  );
  if (!resolver) {
    logger.warn("Staff module not loaded \u2014 availabilityAccessResolver unregistered; denying availability write access");
    return {
      canManageAll: false,
      canManageSelf: false,
      canManageUnavailability: false,
      memberId: null,
      tenantId,
      organizationId,
      unregistered: true
    };
  }
  return resolver.resolveAvailabilityWriteAccess(ctx);
}
async function assertAvailabilityWriteAccess(ctx, params, translate) {
  const access = await resolveAvailabilityWriteAccess(ctx);
  if (access.unregistered) throw buildStaffModuleNotLoadedError();
  if (access.canManageAll) return access;
  if (!access.canManageSelf) throw buildForbiddenError(translate);
  if (!access.memberId || params.subjectType !== "member" || params.subjectId !== access.memberId) {
    throw buildForbiddenError(translate);
  }
  if (params.requiresUnavailability && !access.canManageUnavailability) {
    throw buildForbiddenError(translate);
  }
  return access;
}
function resolveAvailabilityActorId(auth) {
  if (auth) {
    if (typeof auth.sub === "string" && auth.sub.trim().length > 0) return auth.sub;
    if (typeof auth.userId === "string" && auth.userId.trim().length > 0) return auth.userId;
    if (typeof auth.keyId === "string" && auth.keyId.trim().length > 0) return auth.keyId;
  }
  return "system";
}
export {
  assertAvailabilityWriteAccess,
  resolveAvailabilityActorId,
  resolveAvailabilityWriteAccess
};
//# sourceMappingURL=access.js.map
