"""User management service — framework-agnostic CRUD for users.

Uses domain exceptions from app.domain.errors. The router handles
HTTP concerns, auth, audit logging, and commit.
"""

# Enable future language features for compatibility
from __future__ import annotations

# Import uuid
import uuid

# Import Session from sqlalchemy.orm
from sqlalchemy.orm import Session

# Import hash_password from app.auth
from app.auth import hash_password

# Import  from app.domain.errors
from app.domain.errors import (
    BusinessRuleViolation,
    DuplicateEntityError,
    EntityNotFoundError,
)

# Import User from app.models.user
from app.models.user import User

# Assign VALID_ROLES = {"admin", "red_tech", "blue_tech", "red_lead", "blue_lead", "viewer"}
VALID_ROLES = {"admin", "red_tech", "blue_tech", "red_lead", "blue_lead", "viewer"}


# Define function list_users
def list_users(db: Session) -> list[User]:
    """Return a list of all users ordered by username."""
    # Return db.query(User).order_by(User.username).all()
    return db.query(User).order_by(User.username).all()


# Define function create_user
def create_user(
    # Entry: db
    db: Session,
    *,
    # Entry: username
    username: str,
    # Entry: email
    email: str | None,
    # Entry: password
    password: str,
    # Entry: role
    role: str,
) -> User:
    """Create a new user.

    Raises DuplicateEntityError if username already exists.
    Raises BusinessRuleViolation if role is invalid.
    Does not commit; the router handles that.
    """
    # Assign existing = db.query(User).filter(User.username == username).first()
    existing = db.query(User).filter(User.username == username).first()
    # Check: existing
    if existing:
        # Raise DuplicateEntityError
        raise DuplicateEntityError("User", "username", username)

    # Check: role not in VALID_ROLES
    if role not in VALID_ROLES:
        # Raise BusinessRuleViolation
        raise BusinessRuleViolation(
            f"Invalid role '{role}'. Must be one of: {', '.join(sorted(VALID_ROLES))}"
        )

    # Assign user = User(
    user = User(
        # Keyword argument: username
        username=username,
        # Keyword argument: email
        email=email,
        # Keyword argument: hashed_password
        hashed_password=hash_password(password),
        # Keyword argument: role
        role=role,
    )
    # Stage new record(s) for database insertion
    db.add(user)
    # Return user
    return user


# Define function get_user_or_raise
def get_user_or_raise(db: Session, user_id: uuid.UUID) -> User:
    """Return a user by ID or raise EntityNotFoundError."""
    # Assign user = db.query(User).filter(User.id == user_id).first()
    user = db.query(User).filter(User.id == user_id).first()
    # Check: user is None
    if user is None:
        # Raise EntityNotFoundError
        raise EntityNotFoundError("User", str(user_id))
    # Return user
    return user


# Define function update_user
def update_user(db: Session, user_id: uuid.UUID, **fields: object) -> User:
    """Update one or more fields of an existing user.

    Raises EntityNotFoundError if user does not exist.
    Raises BusinessRuleViolation if role is invalid.
    Handles 'password' by hashing and storing as 'hashed_password'.
    Does not commit; the router handles that.
    """
    # Assign user = get_user_or_raise(db, user_id)
    user = get_user_or_raise(db, user_id)
    # Assign update_data = dict(fields)
    update_data = dict(fields)

    # Check: "role" in update_data and update_data["role"] not in VALID_ROLES
    if "role" in update_data and update_data["role"] not in VALID_ROLES:
        # Raise BusinessRuleViolation
        raise BusinessRuleViolation(
            f"Invalid role '{update_data['role']}'. Must be one of: {', '.join(sorted(VALID_ROLES))}"
        )

    # Check: "password" in update_data
    if "password" in update_data:
        # Assign update_data["hashed_password"] = hash_password(str(update_data.pop("password")))
        update_data["hashed_password"] = hash_password(str(update_data.pop("password")))

    # Iterate over update_data.items()
    for field, value in update_data.items():
        # Call setattr()
        setattr(user, field, value)

    # Return user
    return user
