import { getUser, listUsers, createUser as createUserApi, updateUser as updateUserApi, deleteUser, purgeUser, resetUser, findUserByLogin, } from '../../clients/am-api.js';
// Re-export primary API operations from client
export { getUser, listUsers, deleteUser, purgeUser, resetUser };
/**
 * Retrieves details of a user by login (email).
 * This searches through paginated results to find the user.
 *
 * @param client - Account Manager client
 * @param login - User login (email)
 * @returns User details
 * @throws Error if user is not found
 */
export async function getUserByLogin(client, login) {
    const user = await findUserByLogin(client, login);
    if (!user) {
        throw new Error(`User ${login} not found`);
    }
    return user;
}
/**
 * Creates a new user.
 *
 * @param client - Account Manager client
 * @param options - Create options (user details)
 * @returns Created user
 */
export async function createUser(client, options) {
    return createUserApi(client, options.user);
}
/**
 * Updates an existing user.
 *
 * @param client - Account Manager client
 * @param options - Update options (userId, changes)
 * @returns Updated user
 */
export async function updateUser(client, options) {
    return updateUserApi(client, options.userId, options.changes);
}
/**
 * Grants a role to a user, optionally with scope.
 * This updates the user's roles and roleTenantFilter.
 *
 * @param client - Account Manager client
 * @param options - Grant options (userId, role, optional scope)
 * @returns Updated user
 */
export async function grantRole(client, options) {
    const { role, roleEnumName } = options;
    // First get the current user
    const user = await getUser(client, options.userId);
    // Build updated roles (uses role ID format, e.g. 'bm-admin')
    const currentRoles = Array.isArray(user.roles) ? user.roles.map((r) => (typeof r === 'string' ? r : r.id || '')) : [];
    const updatedRoles = currentRoles.includes(role) ? currentRoles : [...currentRoles, role];
    // Build updated roleTenantFilter (uses roleEnumName format, e.g. 'ECOM_ADMIN')
    let roleTenantFilter = user.roleTenantFilter || '';
    if (options.scope) {
        const scopes = options.scope.split(',');
        // Parse existing filter
        const filters = roleTenantFilter.split(';').filter(Boolean);
        const filterMap = new Map();
        for (const filter of filters) {
            const [r, tenants] = filter.split(':');
            if (tenants) {
                filterMap.set(r, tenants.split(','));
            }
        }
        // Add new scopes
        const existingScopes = filterMap.get(roleEnumName) || [];
        const allScopes = [...new Set([...existingScopes, ...scopes])];
        filterMap.set(roleEnumName, allScopes);
        // Rebuild filter string
        roleTenantFilter = Array.from(filterMap.entries())
            .map(([r, tenants]) => `${r}:${tenants.join(',')}`)
            .join(';');
    }
    return updateUser(client, {
        userId: options.userId,
        changes: {
            roles: updatedRoles,
            roleTenantFilter: roleTenantFilter || undefined,
        },
    });
}
/**
 * Revokes a role from a user, optionally removing specific scope.
 *
 * @param client - Account Manager client
 * @param options - Revoke options (userId, role, optional scope)
 * @returns Updated user
 */
export async function revokeRole(client, options) {
    const { role, roleEnumName } = options;
    // First get the current user
    const user = await getUser(client, options.userId);
    // Build updated roles (uses role ID format, e.g. 'bm-admin')
    const currentRoles = Array.isArray(user.roles) ? user.roles.map((r) => (typeof r === 'string' ? r : r.id || '')) : [];
    let updatedRoles = currentRoles;
    // Build updated roleTenantFilter (uses roleEnumName format, e.g. 'ECOM_ADMIN')
    let roleTenantFilter = user.roleTenantFilter || '';
    if (!options.scope) {
        // Remove entire role
        updatedRoles = currentRoles.filter((r) => r !== role);
        // Remove all scopes for this role
        const filters = roleTenantFilter.split(';').filter(Boolean);
        roleTenantFilter = filters.filter((f) => !f.startsWith(`${roleEnumName}:`)).join(';');
    }
    else {
        // Remove specific scope
        const scopes = options.scope.split(',');
        const filters = roleTenantFilter.split(';').filter(Boolean);
        const filterMap = new Map();
        for (const filter of filters) {
            const [r, tenants] = filter.split(':');
            if (tenants) {
                filterMap.set(r, tenants.split(','));
            }
        }
        const existingScopes = filterMap.get(roleEnumName) || [];
        const updatedScopes = existingScopes.filter((s) => !scopes.includes(s));
        if (updatedScopes.length > 0) {
            filterMap.set(roleEnumName, updatedScopes);
        }
        else {
            filterMap.delete(roleEnumName);
        }
        roleTenantFilter = Array.from(filterMap.entries())
            .map(([r, tenants]) => `${r}:${tenants.join(',')}`)
            .join(';');
    }
    return updateUser(client, {
        userId: options.userId,
        changes: {
            roles: updatedRoles.length > 0 ? updatedRoles : undefined,
            roleTenantFilter: roleTenantFilter || undefined,
        },
    });
}
//# sourceMappingURL=index.js.map