"""
Dependency injection for common utilities and auth
"""
from typing import Optional
from fastapi import Depends
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.security import get_current_user
from app.models.user import User


def get_current_company_id(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> Optional[str]:
    """
    Dependency that returns the authenticated user's company_id.
    Use this in route handlers that need to scope queries to the correct tenant.
    """
    cid = getattr(current_user, "company_id", None)
    if cid:
        return cid
    # Fallback: resolve via user's branch
    if getattr(current_user, "branch_id", None):
        from app.models.branch import Branch
        branch = db.query(Branch).filter(Branch.id == current_user.branch_id).first()
        if branch and branch.company_id:
            return branch.company_id
    return None
