# utils/access.py
from sqlalchemy import or_
from models import Employee, EmployeeInstituteAccess

def visible_employee_query(current_user, base_query=None):
    """
    Returns a SQLAlchemy query filtered to employees visible to current_user:
    - Admin/HR: all employees
    - If user has institute mappings: all employees in those institutes + self
    - Else: self only
    """
    q = base_query or Employee.query

    role_name = (getattr(current_user.role, "name", "") or "").lower()
    if role_name in ("admin", "hr"):
        return q

    allowed = [r.institute for r in EmployeeInstituteAccess.query
               .filter_by(viewer_employee_id=current_user.id)
               .all()]

    if allowed:
        return q.filter(or_(Employee.id == current_user.id, Employee.location.in_(allowed)))

    return q.filter(Employee.id == current_user.id)