from __future__ import annotations

from fastapi import Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from sqlalchemy import select

from app.core.db.deps import get_common_db
from app.core.security.jwt_tokens import decode_token
from app.modules.core.iam.models import User

bearer = HTTPBearer(auto_error=False)

def get_current_user_jwt(
    creds: HTTPAuthorizationCredentials | None = Depends(bearer),
    db: Session = Depends(get_common_db),
) -> User | None:
    if not creds or not creds.credentials:
        return None
    data = decode_token(creds.credentials)
    if data.get("typ") != "access":
        return None

    user_id = int(data.get("sub", 0) or 0)
    if not user_id:
        return None
    user = db.execute(select(User).where(User.id == user_id)).scalar_one_or_none()
    if not user or not user.is_active:
        return None
    return user

def require_jwt_user(user: User | None = Depends(get_current_user_jwt)) -> User:
    if not user:
        raise PermissionError("Not authenticated (JWT)")
    return user
