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)

# Post new role
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_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


# Get list of all roles
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
    statement = select(Role)
    results = session.exec(statement).all()
    return results


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