"""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.
"""

from __future__ import annotations

import uuid

from sqlalchemy.orm import Session

from app.auth import hash_password
from app.domain.errors import BusinessRuleViolation, DuplicateEntityError, EntityNotFoundError
from app.models.user import User

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


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()


def create_user(
    db: Session,
    *,
    username: str,
    email: str | None,
    password: str,
    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.
    """
    existing = db.query(User).filter(User.username == username).first()
    if existing:
        raise DuplicateEntityError("User", "username", username)

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

    user = User(
        username=username,
        email=email,
        hashed_password=hash_password(password),
        role=role,
    )
    db.add(user)
    return user


def get_user_or_raise(db: Session, user_id: uuid.UUID) -> User:
    """Return a user by ID or raise EntityNotFoundError."""
    user = db.query(User).filter(User.id == user_id).first()
    if user is None:
        raise EntityNotFoundError("User", str(user_id))
    return 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.
    """
    user = get_user_or_raise(db, user_id)
    update_data = dict(fields)

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

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

    for field, value in update_data.items():
        setattr(user, field, value)

    return user
