from fastapi import Depends, HTTPException
from sqlalchemy import select

from ..auth import get_current_account
from ..models import User, UserRole
from ..db import get_session

# Role hierarchy
ROLE_RANK = {UserRole.VIEWER: 0, UserRole.STEWARD: 1, UserRole.ADMIN: 2}


def require_min_role(min_role: UserRole):
    """Dependency to require minimum role"""

    async def check_role(user: User = Depends(get_current_user_dependency)):
        if ROLE_RANK.get(user.role, 0) < ROLE_RANK[min_role]:
            raise HTTPException(
                403,
                f"Insufficient permissions. Requires {min_role.value} role or higher. Current role: {user.role.value}",
            )

        return user

    return check_role


async def get_current_user_dependency(
    account_id: str = Depends(get_current_account), db=Depends(get_session)
) -> User:
    """Get current user from account context"""
    user = await db.execute(select(User).where(User.account_id == account_id).limit(1))
    user = user.scalar_one_or_none()

    if not user:
        raise HTTPException(401, "User not found for account")

    return user


# Shortcuts for common patterns
require_viewer = require_min_role(UserRole.VIEWER)
require_steward = require_min_role(UserRole.STEWARD)
require_admin = require_min_role(UserRole.ADMIN)
