import backend_fastapi.models as models
from .database import async_session
import backend_fastapi.schemas as schemas
from sqlalchemy import select, update, delete
from fastapi.exceptions import HTTPException
async def add_role(role: schemas.RoleCreate):
    async with async_session() as session:
        model = models.Role(name = role.name)
        session.add(model)
        await session.flush()
        await session.commit()
        return model
    
async def get_role_all():
    async with async_session() as session:
        result = await session.scalars(select(models.Role))
        return result.all()
        
async def delete_role(id: int):
    async with async_session() as session:
        data = await session.scalars(select(models.Role).filter(models.Role.id == id))
        result = data.one_or_none()
        if not result:
            raise HTTPException(status_code=404, detail="Item not found")
        await session.execute(delete(models.Role).filter(models.Role.id == id))
        await session.commit()
        return result
        
    
async def update_role(role: schemas.Role, id: int):
    async with async_session() as session:
        query = update(models.Role).filter(models.Role.id == id).values(name = role.name)
        await session.execute(query)
        await session.commit()
        return {f"{id=} был обновлен"}

async def add_user(user: schemas.UserCreate):
    async with async_session() as session:
        model = models.User(
            **user.model_dump()
            )
        session.add(model)
        await session.flush()
        await session.commit()
        return model
    


