"""
Utility functions for role-based access control
"""
from sqlalchemy.orm import Session
from ...auth.models.user import User
from ...auth.models.role import Role

def get_user_role_name(user: User, db: Session) -> str:
    """Get the role name for a user"""
    if not user or not user.role_id:
        return 'customer'
    try:
        role = db.query(Role).filter(Role.id == user.role_id).first()
        return role.name if role else 'customer'
    except Exception:
        return 'customer'

def is_admin(user: User, db: Session) -> bool:
    """Check if user is admin"""
    return get_user_role_name(user, db) == 'admin'

def is_staff(user: User, db: Session) -> bool:
    """Check if user is staff"""
    return get_user_role_name(user, db) == 'staff'

def is_accountant(user: User, db: Session) -> bool:
    """Check if user is accountant"""
    return get_user_role_name(user, db) == 'accountant'

def is_customer(user: User, db: Session) -> bool:
    """Check if user is customer"""
    return get_user_role_name(user, db) == 'customer'

def can_access_all_payments(user: User, db: Session) -> bool:
    """Check if user can see all payments (admin or accountant)"""
    role_name = get_user_role_name(user, db)
    return role_name in ['admin', 'accountant']

def can_access_all_invoices(user: User, db: Session) -> bool:
    """Check if user can see all invoices (admin or accountant)"""
    role_name = get_user_role_name(user, db)
    return role_name in ['admin', 'accountant']

def can_create_invoices(user: User, db: Session) -> bool:
    """Check if user can create invoices (admin, staff, or accountant)"""
    role_name = get_user_role_name(user, db)
    return role_name in ['admin', 'staff', 'accountant']

def can_manage_users(user: User, db: Session) -> bool:
    """Check if user can manage users (admin only)"""
    return is_admin(user, db)

