from datetime import datetime, timezone

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session

from .core.database import InternalSession, PlatformSession
from .core.security import decode_access_token
from .db_models.internal import SesionAdmin, UsuarioAdmin

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")


def get_internal_db():
    db = InternalSession()
    try:
        yield db
    finally:
        db.close()


def get_platform_db():
    db = PlatformSession()
    try:
        yield db
    finally:
        db.close()


def get_current_admin(
    token: str = Depends(oauth2_scheme),
    db: Session = Depends(get_internal_db),
) -> UsuarioAdmin:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Credenciales inválidas o expiradas",
        headers={"WWW-Authenticate": "Bearer"},
    )

    payload = decode_access_token(token)
    if payload is None:
        raise credentials_exception

    user_id = payload.get("sub")
    if user_id is None:
        raise credentials_exception

    session = (
        db.query(SesionAdmin)
        .filter(
            SesionAdmin.token == token,
            SesionAdmin.fecha_expiracion > datetime.now(timezone.utc),
        )
        .first()
    )
    if session is None:
        raise credentials_exception

    user = (
        db.query(UsuarioAdmin)
        .filter(UsuarioAdmin.id_usuario == user_id, UsuarioAdmin.activo == True)
        .first()
    )
    if user is None:
        raise credentials_exception

    return user
