from fastapi import APIRouter, Depends, Header
from sqlalchemy.orm import Session
from jose import jwt, JWTError
from datetime import datetime

from app.core.database import get_db
from app.core.security import SECRET_KEY, ALGORITHM
from app.models.token_blacklist import TokenBlacklist
from app.utils.logger import get_logger

logger = get_logger(__name__)
router = APIRouter()


@router.get("/check-token")
async def check_token_validity(
    authorization: str = Header(None),
    db: Session = Depends(get_db)
):
    """
    Check if current token is still valid (not revoked)
    Used by frontend for cross-browser logout detection
    """
    try:
        if not authorization or not authorization.startswith("Bearer "):
            return {"valid": False, "reason": "no_token"}

        token = authorization.replace("Bearer ", "")

        # Decode token
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            jti = payload.get("jti")
            exp = payload.get("exp")

            # Check if token is expired
            if exp and datetime.utcnow().timestamp() > exp:
                return {"valid": False, "reason": "expired"}

            # Check if token is blacklisted
            if jti:
                blacklisted = db.query(TokenBlacklist).filter(
                    TokenBlacklist.token_jti == jti
                ).first()

                if blacklisted:
                    return {
                        "valid": False,
                        "reason": "revoked",
                        "revoked_at": blacklisted.revoked_at.isoformat()
                    }

                try:
                    from app.services.session_tracking_service import SessionTrackingService
                    SessionTrackingService(db).touch_session(jti)
                except Exception:
                    pass

            return {"valid": True}

        except JWTError as e:
            logger.warning(f"Invalid token: {e}")
            return {"valid": False, "reason": "invalid"}

    except Exception as e:
        logger.error(f"Token check error: {e}")
        return {"valid": False, "reason": "error"}
