# UpdateUser

## Permission Scope

user

## Overview

UpdateUser modifies the name or email of an existing user account. This command is intended for administrators who need to update any user's profile regardless of the user's current status (PENDING, ACTIVE, or INACTIVE). Email and name are optional in the update input, but at least one must be provided.

This command supports profile corrections such as legal name changes and email address updates.

## Business Rules

- User must exist
- At least one field (name or email) must be provided
- Name, if provided, must be non-empty
- Email, if provided, must follow valid email format
- Email must be unique across all users (active and inactive); case-insensitive comparison
- Updating is allowed on users in any status (PENDING, ACTIVE, INACTIVE)
- Status is not part of the update input (use activateUser/deactivateUser/reactivateUser for status changes)
- Generates USER_UPDATED audit event with actor ID, timestamp, and changed fields

## Process Flow

```mermaid
flowchart TD
    A[Receive update request] --> B{User exists?}
    B -->|No| C[Return error: USER_NOT_FOUND]
    B -->|Yes| D{At least one field provided?}
    D -->|No| E[Return error: MISSING_REQUIRED_FIELD]
    D -->|Yes| F{Name provided and empty?}
    F -->|Yes| G[Return error: INVALID_NAME]
    F -->|No| H{Email provided?}
    H -->|Yes| I{Valid email format?}
    I -->|No| J[Return error: INVALID_EMAIL]
    I -->|Yes| K{Email unique?}
    K -->|No| L[Return error: USER_ALREADY_EXISTS]
    K -->|Yes| M[Update user record]
    H -->|No| M
    M --> N[Log USER_UPDATED audit event]
    N --> O[Return updated user]
```

## External Dependencies

- None

## Error Scenarios

- **USER_NOT_FOUND**: Specified user ID does not exist
- **MISSING_REQUIRED_FIELD**: One or more required fields are missing or empty
- **INVALID_NAME**: Name is empty or whitespace only
- **INVALID_EMAIL**: Email does not follow valid email format
- **USER_ALREADY_EXISTS**: Email address is already registered by another user

## Test Cases

- updates user name
- updates user email
- updates both name and email
- updates user in PENDING status
- updates user in ACTIVE status
- updates user in INACTIVE status
- returns error when user does not exist
- returns error when no fields are provided
- returns error when name is empty
- returns error when name is whitespace only
- returns error when email format is invalid
- returns error when email is already used by another user
- succeeds when email is unchanged (same as current)
