from fastapi import APIRouter, Depends
from ..utils import engine, get_session
from sqlmodel import Session, select, SQLModel, or_
from sqlalchemy.exc import NoResultFound
from ..models.role import Role
from datetime import datetime

router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)


@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
    """
    Post a new role.

    Parameters
    ----------
    role : Role
        Role that is to be added to the database.
    session : Session
        SQL session that is to be used to add the role.
        Defaults to creating a dependency on the running SQL model session.
    """
    statement = select(Role).where(Role.id == role.id)
    try:
        result = session.exec(statement).one()
        return False
    except NoResultFound:
        session.add(role)
        session.commit()
        session.refresh(role)
        return role


@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
    """
    Get list of all roles.

    Parameters
    ----------
    session : Session
        SQL session that is to be used to get the roles.
        Defaults to creating a dependency on the running SQL model session.
    """
    statement = select(Role)
    results = session.exec(statement).all()
    return results


@router.get("/active")
async def read_roles(session: Session = Depends(get_session)):
    """
    Get list of active roles.

    Parameters
    ----------
    session : Session
        SQL session that is to be used to get the roles.
        Defaults to creating a dependency on the running SQL model session.
    """
    statement = select(Role).where(Role.is_active == True)
    results = session.exec(statement).all()
    return results


@router.put("/{role_id}/activate")
async def activate_role(
    role_id: str = None,
    session: Session = Depends(get_session),
):
    """
    Activate a role using the role ID as a key.

    Parameters
    ----------
    role_id : str
        ID of role to be activated.
    session : Session
        SQL session that is to be used to activate the role.
        Defaults to creating a dependency on the running SQL model session.
    """
    statement = 