/**
 * Self-service password change is modelled as a real, admin-revocable RBAC
 * permission — NOT an exception to the RBAC path. Every new user gets a
 * personal RbacDefinition (`self-<userId>`) granting the `set-own-password`
 * operation, gated at creation time by the `allowSelfPasswordChange` system
 * setting. Admins disable it for an individual by deleting that definition,
 * or for future users by flipping the setting.
 */

import type { RbacDefinitionService } from '../services/rbac-definition.service.js';

/** Operation that gates `POST /api/v1/users/me/password`. */
export const SET_OWN_PASSWORD_OPERATION = 'set-own-password';

/** Name of a user's personal RbacDefinition (currently just self password). */
export function selfRbacName(userId: string): string {
  return `self-${userId}`;
}

/**
 * Grant a user the default self-service password-change permission.
 * Idempotent (upsert by name) — safe to call on every creation/bootstrap.
 */
export async function grantSelfPasswordPermission(
  rbac: RbacDefinitionService,
  user: { id: string; email: string },
): Promise<void> {
  await rbac.upsertByName({
    name: selfRbacName(user.id),
    subjects: [{ kind: 'User', name: user.email }],
    roleBindings: [{ role: 'run', action: SET_OWN_PASSWORD_OPERATION }],
  });
}
