import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { StaffTeamMember } from "../data/entities.js";
const MANAGE_AVAILABILITY_FEATURE = "planner.manage_availability";
const SELF_MANAGE_FEATURE = "staff.my_availability.manage";
const SELF_UNAVAILABILITY_FEATURE = "staff.my_availability.unavailability";
async function resolveAvailabilityWriteAccess(ctx) {
  const auth = ctx.auth;
  const tenantId = auth?.tenantId ?? null;
  const organizationId = ctx.selectedOrganizationId ?? auth?.orgId ?? null;
  if (!auth || !auth.sub || auth.isApiKey) {
    return {
      canManageAll: false,
      canManageSelf: false,
      canManageUnavailability: false,
      memberId: null,
      tenantId,
      organizationId
    };
  }
  const rbac = ctx.container.resolve("rbacService");
  const canManageAll = await rbac.userHasAllFeatures(
    auth.sub,
    [MANAGE_AVAILABILITY_FEATURE],
    { tenantId, organizationId }
  );
  if (canManageAll) {
    return {
      canManageAll: true,
      canManageSelf: true,
      canManageUnavailability: true,
      memberId: null,
      tenantId,
      organizationId
    };
  }
  const [canManageSelf, canManageUnavailability] = await Promise.all([
    rbac.userHasAllFeatures(auth.sub, [SELF_MANAGE_FEATURE], { tenantId, organizationId }),
    rbac.userHasAllFeatures(auth.sub, [SELF_UNAVAILABILITY_FEATURE], { tenantId, organizationId })
  ]);
  if (!canManageSelf) {
    return {
      canManageAll: false,
      canManageSelf: false,
      canManageUnavailability: false,
      memberId: null,
      tenantId,
      organizationId
    };
  }
  const em = ctx.container.resolve("em");
  const member = await findOneWithDecryption(
    em,
    StaffTeamMember,
    { userId: auth.sub, deletedAt: null },
    void 0,
    { tenantId, organizationId }
  );
  return {
    canManageAll: false,
    canManageSelf,
    canManageUnavailability,
    memberId: member?.id ?? null,
    tenantId,
    organizationId
  };
}
export {
  MANAGE_AVAILABILITY_FEATURE,
  SELF_MANAGE_FEATURE,
  SELF_UNAVAILABILITY_FEATURE,
  resolveAvailabilityWriteAccess
};
//# sourceMappingURL=availabilityAccess.js.map
